我正在尝试创建一个名为Dfetch()的C函数,该函数在Lua中注册为fetch().我正在寻找分层,以便我可以将dog.beagle.fetch()称为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}};
在我的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);
蒂姆,谢谢
void myregister(lua_State *L, const char *libname, const char *sublibname, const luaL_Reg *lib) { // create 'libname' table lua_newtable(L); // no sublib: just import our library functions directly into lib and we're done if (sublibname == NULL) { luaL_setfuncs(L, lib, 0); } // sublib: create a table for it, import functions to it, add to parent lib else { lua_newtable(L); luaL_setfuncs(L, lib, 0); lua_setfield(L, -2, sublibname); } lua_setglobal(L, libname); }