lua-users home
lua-l archive

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


2014-08-12 19:09 GMT+02:00 Tim Hill <drtimhill@gmail.com>:
>
> On Aug 12, 2014, at 8:48 AM, Dirk Laurie <dirk.laurie@gmail.com> wrote:
>
> 4. If you compile a function using `load` or `loadstring`, its _ENV is one
> of:
>   a. An _ENV parameter.
>   b. The _ENV specified in the `load`.
>   c. An _ENV upvalue.
>
>
> I think it’s always either the distinguished environment (the one stored in
> the registry at a well-known key) or the explicit table specified as an
> argument to load().

It's only the one specified in the registry if that still happens to be
the current upvalue called _ENV. And even the one in the registry
may not be the one you started with. You can assign something
to debug.getregistry[2]; not recommended, though.

Here is a little demo. Save it as 'env.lua'; it does not run in the IDE
because of different local scope.

local _ENV = {id="_ENV local to `do` block"}

local function f1() return _ENV, id end
print("case c:",f1())
local _ENV1=_ENV
_ENV = {id="_ENV shadowing previous local variable"}
print("case c:",f1())
print "case c: _ENV is the table currently in this upvalue"
local function f2(_ENV) return _ENV, id end
print("case a:",f2(_ENV1))
print("case a:",f2(_ENV))
print "case a: _ENV is the table passed as argument to the function"
local f3 = load("return _ENV,id",nil,nil,_ENV1)
print("case b:",f3())
local f3 = load("return _ENV,id",nil,nil,_ENV)
print("case b:",f3())
print "case b: _ENV is the table passed as argument to load"
end

$ lua53 env.lua
table: 0x10f85f0    _ENV as in original registry
case c:    table: 0x1100430    _ENV local to `do` block
case c:    table: 0x10fffe0    _ENV shadowing previous local variable
case c: _ENV is the table currently in this upvalue
case a:    table: 0x1100430    _ENV local to `do` block
case a:    table: 0x10fffe0    _ENV shadowing previous local variable
case a: _ENV is the table passed as argument to the function
case b:    table: 0x1100430    _ENV local to `do` block
case b:    table: 0x10fffe0    _ENV shadowing previous local variable
case b: _ENV is the table passed as argument to load