繁体   English   中英

从C ++调用Lua 5.2函数

[英]Calling Lua 5.2 function from C++

我对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);

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

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

但请确保测试luaL_loadfilelua_pcall的返回码。 使用luaL_dofile可能会更好。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM