尝试在Lua中使用嵌套表调用函数。

我正在尝试创建一个名为Dfetch()的C函数,将它在Lua中注册为fetch()。我希望它被分层,这样我可以从Lua中调用dog.beagle.fetch()作为函数。这只是更好地组织代码的帮助。以下是我拥有的内容,但它没有调用我的C函数。如果只做全局而不是子表,C函数会被调用。我是Lua的新手,所以我认为我只是设置表的错误。

{
    luaL_newmetatable(L, libname);
    lua_newtable(L); luaL_setfuncs(L,l,0);
    lua_pushvalue(L,-1);
    if(sublibname != NULL)
    {
        lua_newtable(L);
        lua_setfield(L, -2, sublibname);
    }
    lua_setglobal(L, libname);
}

luaL_Reg fidofuncModule[] = { {"fetch", Dfetch}, {NULL, NULL}};

在我的main()中,我调用以下内容:

lua_State * execContext = luaL_newstate();
//adding lua basic library
luaL_openlibs(execContext);

myregister(execContext, "dog", "beagle", fidofuncModule);

strcpy(buff, "dog.beagle.fetch();");
errorcode = luaL_loadbuffer(execContext, buff, strlen(buff), "line");
errorcode = lua_pcall(execContext, 0, 0, 0);

if (errorcode)
{
  printf("%s", lua_tostring(execContext, -1));
  lua_pop(execContext, 1);  /* pop error message from the stack */
}
//cleaning house
lua_close(execContext);

谢谢,Tim

点赞
用户107090
用户107090

fetch正在注册到libname中,而不是sublibname中。要确认,请在调用之前向buff添加print(dog.fetch)

尝试这个:

void myregister(lua_State *L, const char *libname, const char *sublibname, const luaL_Reg *l)
{
    lua_newtable(L);
    lua_pushvalue(L,-1);
    lua_setglobal(L, libname);
    if(sublibname != NULL)
    {
        lua_newtable(L);
        lua_pushvalue(L,-1);
        lua_setfield(L, -3, sublibname);
    }
    luaL_setfuncs(L,l,0);
}
2012-11-13 19:42:06
用户501459
用户501459
void myregister(lua_State *L, const char *libname, const char *sublibname, const luaL_Reg *lib)
{
    // 创建名为 'libname' 的表
    lua_newtable(L);

    // 没有子库:将我们的库函数直接导入到lib中,完成
    if (sublibname == NULL)
    {
        luaL_setfuncs(L, lib, 0);
    }
    // 子库:为其创建一个表,将函数导入到其中,添加到父级库中
    else
    {
        lua_newtable(L);
        luaL_setfuncs(L, lib, 0);
        lua_setfield(L, -2, sublibname);
    }

    lua_setglobal(L, libname);
}
2012-11-13 19:48:44