lua-users home
lua-l archive

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

On Wed, Jun 9, 2010 at 11:10 AM, Roberto Ierusalimschy
<> 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

>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 "" 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.

[2] as I've written elsewhere concerning module/luaL_register and
functions like getfenv/setfenv/error that depend on stack levels