It is my understanding that in Lua 5.2 that environments are stored in upvalues named I would like to load a file with some functions and use the chunk to inject those functions into various environments. Example:
Is this possible from within Lua? The only examples I can find of modifying this upvalue are with the C api (another example from C api), but I am trying to do this from within Lua. Is this possible? Edit: I'm unsure of accepting answers using the debug library. The docs state that the functions may be slow. I'm doing this for efficiency so that entire chunks don't have to be parsed from strings (or a file, even worse) just to inject variable definitions into various environments. Edit: Looks like this is impossible: Recreating setfenv() in Lua 5.2 Edit: I suppose the best way for me to do this is to bind a C function that can modify the environment. Though this is a much more annoying way of going about it. Edit: I believe a more natural way to do this would be to load all chunks into separate environments. These can be "inherited" by any other environment by setting a metatable that refers to a global copy of a chunk. This does not require any upvalue modification post-load, but still allows for multiple environments with those function definitions. | |||||||||||||||||
|
The simplest way to allow a chunk to be run in different environments is to make this explicit and have it receive an environment. Adding this line at the top of the chunk achieves this:
Now you can call There, no Although it will be clear if your chunk contains that line, you can add it at load time, by writing a suitable reader function that first sends that line and then the contents of the file. | |||||
|
I do not understand why you want to avoid using the debug library, while you are happy to use a C function (neither is possible in a sandbox.) It can be done using
Now load any chunk like this:
It will initially inherit the enclosing
and insert a value for 'x':
Now when you run the chunk, it should see the value for
=> |
联系客服