在C++中从table.subtable调用lua函数

我正在尝试从C++中调用lua函数, 其中函数在全局表的子表中。我使用的是从源代码编译的lua版本5.2.*。

Lua function

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

C++ code

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: unprotected error in call to Lua API (attempt to index a nil value)

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

我错过了什么?

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

谢谢!


这是我用来创建globaltable的代码:

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?

点赞
用户221509
用户221509

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-14 09:20:29
用户1107622
用户1107622
lua_newtable(L);
luaL_newmetatable(L, "globaltable");
lua_newtable(L); //创建表
lua_setfield(L, -2, "subtable"); //将表设置为“globaltable”的字段
lua_setglobal(L, "globaltable");

这就是我一直在寻找的。

2012-07-15 10:09:42