summaryrefslogtreecommitdiff
path: root/src/libluaglue/LuaVM.cpp
blob: d5878970c40b5f182973e94959ad401d98ef850d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
#include "LuaVM.hpp"

#include <stdexcept>
#include <sstream>
#include <iostream>

using namespace std;

LuaVM::LuaVM( ) : m_lua( 0 )
{
	initialize( );
}

LuaVM::~LuaVM( )
{
	lua_close( m_lua );
}

lua_State *LuaVM::handle( )
{
	return m_lua;
}

void LuaVM::initialize( )
{
	m_lua = luaL_newstate( );
	
	luaL_openlibs( m_lua );
}

void LuaVM::fullGarbageCollect( )
{
	lua_gc( m_lua, LUA_GCCOLLECT, 0 );
}

void LuaVM::loadSource( const char *sourceFilename )
{
	int res;
	
	m_sourceFilename.assign( sourceFilename );
	
	res = luaL_loadfile( m_lua, m_sourceFilename.c_str( ) );
	if( res != 0 ) {
		ostringstream ss;
		ss << "Can't read Lua source file from file '" << m_sourceFilename << "': " << lua_tostring( m_lua, -1 );
		lua_pop( m_lua, 1 );
		throw std::runtime_error( ss.str( ) );
	}
}

void LuaVM::executeMain( )
{
	int res;
	
	res = lua_pcall( m_lua, 0, LUA_MULTRET, 0 );
	if( res != 0 ) {
		ostringstream ss;
		ss << "Can't execute main body of Lua source file '" << m_sourceFilename << "': " << lua_tostring( m_lua, -1 );
		lua_pop( m_lua, 1 );
		throw std::runtime_error( ss.str( ) );
	}
}

void LuaVM::dumpState( )
{
	lua_rawgeti( m_lua, LUA_REGISTRYINDEX, LUA_RIDX_GLOBALS );
	lua_pushnil( m_lua );
	while( lua_next( m_lua, -2 ) ) {
		if( lua_type( m_lua, -2 ) == LUA_TSTRING ) {
			cout << lua_tostring( m_lua, -2 ) << endl;
		}
		lua_pop( m_lua, 1 );
	}
}