我想了解我们如何将属性公开给 lua 库。
luaL_openlib( L, kName, kVTable, 1 ); // leave "library" on top of stack
有了这个,我就可以只公开函数,因为 kVTable 指的是 luaL_Reg
typedef struct luaL_Reg {
const char *name;
lua_CFunction func;
} luaL_Reg;
例如:用上面的代码。我可以执行以下操作。
local myLib = require "plugin.myLib"
myLib.newFunc();
但是,我想将 Lua Table 作为 CONSTANTS 变量公开给库。
myLib.CONSTANTS.SOME_CONST_1
myLib.CONSTANTS.SOME_CONST_2
等请让我知道如何将我的库中的 lua 表公开为属性。
最佳答案
由于 luaL_openlib
将库表留在堆栈顶部,您可以使用常规 C API 向其添加新字段和子表:
luaL_openlib( L, kName, kVTable, 1 ); // leaves "library" on top of stack
lua_pushstring(L, "CONSTANTS");
lua_newtable(L); // this will be CONSTANTS subtable
lua_pushstring(L, "SOME_CONST_1");
lua_pushnumber(L, 42); // SOME_CONST_1 value
lua_settable(L, -3); // sets SOME_CONST_1
lua_pushstring(L, "SOME_CONST_2");
lua_pushnumber(L, 12345); // SOME_CONST_2 value
lua_settable(L, -3); // sets SOME_CONST_2
lua_settable(L, -3); // sets CONSTANTS table as field of the library table
return 1;
关于c++ - 如何从 C++ 向 Lua 库公开属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18997658/