lua-users home
lua-l archive

Re: Sandboxing a module that clutters the global environment

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


On 10/5/2016 6:31 AM, tyrondis wrote:
Hi *,
I have a 3rd party module that operates and maintains its state in the global environment. Is there anyway I can load this module into a custom context table, so that it uses that table as its _G? I want to be able to have multiple instances of that module, which is currently not possible because of its “Singleton” nature. I could also refactor the 3rd part module but I want to have it untouched to make it easier to apply potential patches to it.
Thanks
Tyr
I've done something like this to run multiple luarocks commands from a single lua state.
Relevant functions:
https://git.io/vPcIG
https://git.io/vPcIW
This was a high-touch process: I actually stuck a breakpoint in the middle of luarocks so I could inspect the environment to see exactly what exactly I needed to shim and what I didn't. Once I knew that (in my case _G and package.loaded) I used a simple shim:
t = setmetatable({}, {__index=old_t})
Table reads should behave the same, but every time a table gets written to, the write goes into the shim instead of the old table. This is shallow, so something like `t.a.b` would leak back into the original t.a, but this is fine for me since luarocks doesn't do anything particularly silly. I use Lua 5.1's setfenv to apply the new environment, but _ENV can be used to similar effect on 5.2/5.3:
http://leafo.net/guides/setfenv-in-lua52-and-above.html

AltStyle によって変換されたページ (->オリジナル) /