当我将 Lua 集成到我的 C 程序中时,我一直在使用static
指向 C 结构的指针来存储我需要在绑定到 Lua 状态的方法中重用的对象。
但是,一旦我将 Lua 库从主程序中拆分出来,这将不起作用,因此我似乎需要使用注册表来存储我的结构。
如何将我的 C 结构指针存储在 Lua 注册表中?
这就是我目前正在做的事情:
static augeas *aug = NULL;
static int lua_aug_get(lua_State *L) {
// Use aug to do something here
/* return the number of results */
return 1;
}
struct lua_State *luaopen_augeas(augeas *a) {
lua_State *L = luaL_newstate();
aug = a; // this clearly does not work
luaL_openlibs(L);
// The methods below will need to access the augeas * struct
// so I need to push it to the registry (I guess)
static const luaL_Reg augfuncs[] = {
{ "get", lua_aug_get },
{ "label", lua_aug_label },
{ "set", lua_aug_set },
{ NULL, NULL }
};
luaL_newlib(L, augfuncs);
lua_setglobal(L, "aug");
return L;
}
编辑:从我在 IRC 上得到的答案看来,我应该使用metatable,所以我目前正在研究这个。