我研究了这个主题并尝试了各种方法,但我无法实现我的想法(我什至不确定这是否可能)。基本上,我有几个用 C 创建的 userdata 对象,可以通过它们的元表访问,如下所示:
主程序.lua
config.display_width = 1280
我想做的是将配置命名空间“强制”到特定的脚本。您已经猜到了,我需要保护一个配置文件,以便限制用户只能处理配置元表。像这样:
配置文件
display_width = 1280
而且我知道我必须在 C 中做这样的事情:
// Register the config metatable and its methods
luaL_loadfile(L, "my_config.cfg");
lua_getglobal(L, "config"); // Is this necessary?
lua_setfenv(L, -2); // I know this has to be used, but how?
lua_pcall(L, 0, 0, 0);
提前谢谢你,这个让我发疯!
PS:作为记录,我真的需要保留配置用户数据,因为它绑定到 C 结构。因此,我不担心在不同环境之间“丢失” Lua 状态或声明的变量。
添加以下信息。这是创建配置用户数据的方式:
const struct luaL_Reg metaconfig[] =
{
{"__index", l_get},
{"__newindex", l_set},
{NULL, NULL}
};
lua_newuserdata(L, sizeof(void *));
luaL_newmetatable(L, "metaconfig");
luaL_register(L, NULL, metaconfig);
lua_setmetatable(L, -2);
lua_setglobal(L, "config");
因此,每次用户从配置用户数据中设置或获取值时,我都会通过__index
or__newindex
方法更新 C 结构。