我是 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 引用手册 ( 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);
最佳答案
下面的代码应该适用于 5.1 和 5.2。
lua_getglobal(luaState, "myLuaFunction");
lua_pcall(luaState, 0, 0, 0);
但一定要测试 luaL_loadfile
和 lua_pcall
的返回码。使用 luaL_dofile
可能会更好。
关于c++ - 从 C++ 调用 Lua 5.2 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15223056/