[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: Simulating getfenv for Lua 5.2
- From: David Manura <dm.lua@...>
- Date: Sat, 12 Jun 2010 20:40:56 -0400
On Wed, Jun 9, 2010 at 11:10 AM, Roberto Ierusalimschy
<roberto@inf.puc-rio.br> wrote:
> 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:
Moreover, if redefining a main function environment, you would need to
take care to use "_ENV = ......" rather than "local _ENV = .....".
The latter creates a different variable. Although there's likely no
need to do that, unless there's some reason to make the environment go
out of scope following main function execution, I am tempted by the
symmetry since any nested environment in the file would also be
declared with "local _ENV = .....", and it emphasizes that the
variable is a lexical with constant binding.
Another danger may occur if one of the module archivers [1] is used to
package multiple Lua modules into a single module. What might
normally be a main function might not be after the archiving
transformation.
>From a standpoint of engineering and larger scale programming, I
really don't like stuff like this in Lua that often works but breaks
in weird cases or transformations [2]. So, I don't recommend
debug.getupvalue(debug.getinfo(2).func, 1) but rather something
explicit like _ENV:import "hello.world" mentioned by Patrick. If you
want to infer _ENV, a more complete way is probably to walk the
lexical structure with debug.getlocal, but again that can fail (if
symbols stripped). Yet another option could be to explicitly register
_ENV in some weak table somewhere each time you declare _ENV.
[1] http://lua-users.org/wiki/BinToCee
[2] as I've written elsewhere concerning module/luaL_register and
functions like getfenv/setfenv/error that depend on stack levels