[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: Simulating getfenv for Lua 5.2
- From: Tomas Lundell <tomas.lundell@...>
- Date: Sat, 12 Jun 2010 11:37:01 +1000
If 'import' is only called from the main function in a module, then you
can safely assume that the environment will be the first upvalue of the
callee function. So, you can use debug.getupvalue to get its value:
function import(fname)
...
local this_env = {}
loadin(fname, this_env)
local _, calling_env = debug.getupvalue(debug.getinfo(2).func,
1)
assert(_ == "_ENV")
calling_env['world'] = this_env
end
(Untested code...)
-- Roberto
That fits the bill. It does feel like you're subverting the system when you're using assumptions like that, but then again perhaps that is intentional.
For Lua 6, if we had some sort of macro facility then that would cover these cases much more nicely:
import hello.world => [macro expansion] =>
local world = import("hello.world")
/ Tom