从C ++调用Lua 5.2函数

时间:2013-03-05 11:50:06

标签: c++ lua lua-5.2

我对Lua很新。 我一直在看一些如何从C ++调用Lua函数的示例代码,但示例代码使用5.1,我试图让它与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参考manuel(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);

1 个答案:

答案 0 :(得分:3)

下面的代码应该适用于5.1和5.2。

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

但请务必测试luaL_loadfilelua_pcall的返回代码。使用luaL_dofile可能会更好。