lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


2011/2/16 Agustín Cordes <agustin@senscape.net>:
> Hi all,
>
> I have researched this subject and tried various approaches but I can't implement the behavior I have in mind (I'm not even sure it's possible). Basically, I have several userdata objects created in C that can be accessed by their metatable, like this:
>
> Main.lua
> --------
>
> config.display_width = 1280
>
> What I'd like to do is to "force" the config namespace to a specific script. You've guessed it, I need to protect a configuration file so that users are restricted to deal only with the config metatable. Like this:
>
> Config.lua
> ----------
>
> display_width = 1280
>
> And I know I have to do something like this in 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);
>
> Thank you in advance, this one is driving me crazy!
>
> Agustín
>
> PS: For the record, I really need to keep the config userdata as it is because it's binded to a C structure. In consequence, I'm not concerned about "losing" the Lua state or declared variables between different environments.


You need to wrap the config userdata in a table because closure
environments must be tables. This basically:

> // Register the config metatable and its methods
> luaL_loadfile(L, "my_config.cfg");
lua_newtable(L);
lua_newtable(L);
> lua_getglobal(L, "config"); // Is this necessary?
lua_setfield(L, -2, "__index");
lua_setmetatable(L, -2);
> lua_setfenv(L, -2); // I know this has to be used, but how?
> lua_pcall(L, 0, 0, 0);

At least, this is what you need to do if I understand your problem...

-- 
- Patrick Donnelly