lua-users home
lua-l archive

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


David Burgess wrote:

I can set the environment of a Lua thread with
lua_setfenv() with a thread as the target.  Does this do
anything other than allow you to retrieve this environment
with lua_getfenv()?

That environment becomes the "global" (level 0) environment
of that thread.
The print function looks there for tostring:

 > function f()
 >>   io.write("io.write test\n")
 >>   print("print test")
 >> end
> > thr = coroutine.create(f)
 > debug.setfenv(thr, {print = print, io = {write = io.write}})
 > f()
 io.write test
 print test
 > assert(coroutine.resume(thr))
 io.write test
 stdin:1: attempt to call a nil value
 stack traceback:
         [C]: in function 'assert'
         stdin:1: in main chunk
         [C]: ?

And loadstring uses it as the f-env of a loaded chunk:

 > function f()
 >>   (loadstring("foo('test')"))()
 >> end
> > thr = coroutine.create(f)
 > debug.setfenv(thr, {foo = function(s) io.write(s, "\n") end})
 > f()
 [string "foo('test')"]:1: attempt to call global 'foo' (a nil value)
 stack traceback:
         [string "foo('test')"]:1: in main chunk
         stdin:2: in function 'f'
         stdin:1: in main chunk
         [C]: ?
 > assert(coroutine.resume(thr))
 test

--
Aaron