lua-users home
lua-l archive

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


Quoth Dubiousjim <lists+lua@jimpryor.net>, on 2012-05-19 22:21:29 -0400:
> I guess my surprise stems from a subtlety about what it means to say a
> function is "newly created". In one sense, the second through fourth of
> the above examples all have functions being "newly created" after the
> setfenv was executed: the code that declares that function and
> constructs a function closure is not executed until after the setfenv.

I don't think that's quite the effect.  The mainy difference is that
functions created by function statements and expressions are always
lexically inside another function, whereas newly-loaded ones are not.
Lua 5.1 manual, section 2.9, "Environments" declares that
"Environments associated with Lua functions are [...] used as the
default environment for nested Lua functions created by the function."

So in your example:

> $ lua-5.1 -e 'flag = true
>     local newg={ flag=false,tostring=tostring,print=print }
>     local fs = {}
>     coroutine.wrap(function()
>         setfenv(0, newg)
>         for i=1,2 do
>             local counter = 0
>             fs[i] = function() counter = counter + 1; return counter, flag end
>         end
>     end)()
>     print(fs[1]())
>     print(fs[1]())
>     print(fs[2]())'
> 1  true
> 2  true
> 1  true
> 
> The closures are not created until the loop executes, as is demonstrated
> by the independence of their counters. But note that they read flag from
> the original thread environment, not from the environment in place when those
> closures are created.

... they're not actually getting their environment directly from the
original thread, but from the surrounding function, which got its
environment from the file function, which got its environment from the
main thread when it was created.  Each of these happens at the time
the inner or outer function expression or load call is evaluated,
respectively.  Note that the second thread environment is never
examined at all.

Thread environments do a lot less than people sometimes assume they do.

   ---> Drake Wilson