小编Tim*_*ham的帖子

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

我正在尝试创建一个名为Dfetch()的C函数,该函数在Lua中注册为fetch().我正在寻找分层,以便我可以将dog.beagle.fetch()称为Lua的函数.它只是有助于更好地组织代码.下面是我的,但它不是调用我的C函数.如果我只是执行全局而不是子表,则调用C函数.我是Lua的新手,所以我想我只是把桌子弄错了.

void myregister(lua_State *L, const char *libname, const char *sublibname, const luaL_Reg *l) 
{ 
    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}};
Run Code Online (Sandbox Code Playgroud)

在我的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 …
Run Code Online (Sandbox Code Playgroud)

c lua nested function

5
推荐指数
1
解决办法
1033
查看次数

标签 统计

c ×1

function ×1

lua ×1

nested ×1