2013-03-05 63 views
5

我對Lua很新。 我一直在尋找一些示例代碼來說明如何從C++調用Lua函數,但示例代碼使用5.1,並且我試圖讓它與5.2一起工作。從C++調用Lua 5.2函數

這裏是有問題的代碼示例有我的評語:

lua_State *luaState = luaL_newstate(); 
luaopen_io(luaState); 
luaL_loadfile(luaState, "myLuaScript.lua"); 
lua_pcall(luaState, 0, LUA_MULTRET, 0); 
//the code below needs to be rewritten i suppose 
lua_pushstring(luaState, "myLuaFunction"); 
//the line of code below does not work in 5.2 
lua_gettable(luaState, LUA_GLOBALSINDEX); 
lua_pcall(luaState, 0, 0, 0); 

我已經在5.2參考曼努埃爾閱讀(http://www.lua.org/manual/5.2/manual.html#8.3)一個需要從註冊表(而不是lua_gettable獲得全球環境上面的聲明),但我無法確定我需要做出哪些更改才能實現此功能。我試過,例如:

lua_pushglobaltable(luaState); 
lua_pushstring(luaState, "myLuaFunction"); 
lua_gettable(luaState, -2); 
lua_pcall(luaState, 0, 0, 0); 
+0

另請參閱http://stackoverflow.com/questions/11093189/lua-updating-from-5-1-lua-globalsindex-problems – lhf 2013-03-05 13:08:56

回答

3

下面的代碼應能在兩個5.1和5.2工作。

lua_getglobal(luaState, "myLuaFunction"); 
lua_pcall(luaState, 0, 0, 0); 

但要確保測試的luaL_loadfilelua_pcall和返回代碼。你可能會更好使用luaL_dofile