1

我试图从 C++ 调用一个 lua 函数,其中函数位于全局表的子表中。我使用从源代码编译的 lua 版本 5.2.*。

Lua 函数

function globaltable.subtable.hello()
 -- do stuff here
end

C++ 代码

lua_getglobal(L, "globaltable");
lua_getfield(L, -1, "subtable");
lua_getfield(L, -1, "hello");
if(!lua_isfunction(L,-1)) return;
    lua_pushnumber(L, x);
    lua_pushnumber(L, y);
    lua_call(L, 2, 0);

但是我无法调用它,我总是得到一个错误

PANIC:调用 Lua API 时出现不受保护的错误(尝试索引 nil 值)

第 3 行:lua_getfield(L, -1, "hello");

我错过了什么?

附带问题:我也很想知道如何调用比这更深的函数 - 比如globaltable.subtable.subsubtable.hello()等。

谢谢!


这就是我用来创建全局表的方法:

int lib_id;
lua_createtable(L, 0, 0);
lib_id = lua_gettop(L);
luaL_newmetatable(L, "globaltable");
lua_setmetatable(L, lib_id);
lua_setglobal(L, "globaltable");

我如何创建 globaltable.subtable?

4

2 回答 2

2

function是 Lua 中的一个关键字,我猜你是如何编译代码的:

-- test.lua
globaltable = { subtable = {} }
function globaltable.subtable.function()
end

运行时:

$ lua test.lua
lua: test.lua:2: '<name>' expected near 'function'

也许您更改了此在线演示文稿的标识符,但检查第 2 行是否 "subtable"确实存在于 中globaltable,因为在第 3 行,堆栈顶部已经是nil.

更新:

要创建多级表,您可以使用以下方法:

lua_createtable(L,0,0); // the globaltable
lua_createtable(L,0,0); // the subtable
lua_pushcfunction(L, somefunction);
lua_setfield(L, -2, "somefunction"); // set subtable.somefunction
lua_setfield(L, -2, "subtable");     // set globaltable.subtable
于 2012-07-14T09:20:29.870 回答
0
lua_newtable(L);
luaL_newmetatable(L, "globaltable");
lua_newtable(L); //Create table
lua_setfield(L, -2, "subtable"); //Set table as field of "globaltable"
lua_setglobal(L, "globaltable");

这就是我一直在寻找的。

于 2012-07-15T10:09:42.270 回答