我对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);
Run Code Online (Sandbox Code Playgroud)
我在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);
Run Code Online (Sandbox Code Playgroud)
下面的代码应该适用于 5.1 和 5.2。
lua_getglobal(luaState, "myLuaFunction");
lua_pcall(luaState, 0, 0, 0);
Run Code Online (Sandbox Code Playgroud)
但请务必测试luaL_loadfile和 的返回码lua_pcall。使用 可能会更好luaL_dofile。