summaryrefslogtreecommitdiff
path: root/src/libluaglue/LuaVM.cpp
blob: 7b165f1d3c40d121b41c03bf706015d287c12f54 (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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
#include "LuaVM.hpp"

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

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 = lua_pcall( m_lua, 0, 0, 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::executeFunction( const string &f )
{
	//int top = lua_gettop( m_lua );
	lua_getglobal( m_lua, f.c_str( ) );	
	int res = lua_pcall( m_lua, 0, LUA_MULTRET, 0 );
	if( res != 0 ) {
		ostringstream ss;
		ss << "Unable to call Lua function '" << f << "': " << lua_tostring( m_lua, -1 );
		lua_pop( m_lua, 1 );
		throw new std::runtime_error( ss.str( ) );
	}
	//int nresults = lua_gettop( m_lua ) - top;
	
	// TODO: return results
}

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 );
	}
}