c++ - 从 C++ 调用 Lua 5.2 函数

标签 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 引用手册 ( 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 可能会更好。

关于c++ - 从 C++ 调用 Lua 5.2 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15223056/

相关文章:

windows - 如何在 luasocket 3 中使用 Lua 5.2

c++ - 包含位字段的结构的大小

C++ 模板元编程 : Different Behavior using Types Aliases vs Inheritance

utf-8 - Lua string.format 使用 UTF8 字符

lua - lua __pairs 的实际实现是什么?

lua - 当 'if a == 40 or 42' 为 47 时,为什么 'true' 评估为 'a'?

c++ - 无法调试 C++ 项目,因为无法静态库启动程序 *.lib

c++ - 通过命令行使用 gcc 编译 win32 应用程序时,如何链接 .rc(资源)文件?

ruby - 难道Lua没有和Ruby的method_missing相媲美的东西吗?

lua - 在 luarocks 中使用代码安装资源