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 19:15:56 -0400:
> I hadn't tried exactly this code, but was simplifying some other tests I
> had run. Apparently, though, calling print will fail with an error if
> tostring isn't visible in the active environment (even if print's
> arguments are all strings). So you need to make newG = { flag = false,
> tostring = tostring }.
> 
> But it still is printing true, contrary to what the documents and my
> understanding of thread environments seems to imply.

Global lookups in a function use the function's environment.  Thread
environments affect _new_ top-level functions created inside that
thread, but the function you pass to coroutine.wrap has already been
created from a function (the one for the entire file) in the first
thread, so setting the thread environment does nothing to it.

Note that creating new functions inside the function where you do the
setfenv(0, ...) will also use the outer function's environment, not
the thread environment.  New top-level functions mainly appear as a
result of loading code:

  foo = true
  local e = { print = print, tostring = tostring, foo = false }
  coroutine.wrap(function() setfenv(0, e); loadstring('print(foo)')() end)()

prints "false", since the function returned by loadstring uses the
environment of the current thread.

   ---> Drake Wilson