首页 文章

从C中的table.subtable调用lua函数

提问于
浏览
1

我试图从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:调用Lua API时出现无保护错误(尝试索引零值)

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

What am I missing?

附带问题:我也想知道如何更深入地调用函数 - 比如 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?

2 回答

  • 0

    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 .

    Update:

    要创建多个级别的表,可以使用以下方法:

    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
    
  • 2
    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");
    

    这就是我想要的 .

相关问题