lua-users home
lua-l archive

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


Nevermind, I think I figured it out.

Rob Hoelz <rob@hoelzro.net> wrote:

> Hello Lua users,
> 
> I thought I understood function environments, but I wrote a small
> piece of code that has me guessing.  Here's the code:
> 
> local p = print
> 
> setfenv(0, setmetatable({}, {__index = _G, __newindex = function(_, k,
> v) p 'uh-oh'
> end}))
> 
> print 'still here'
> print = nil 
> io.write('print: ' .. tostring(print) .. '\n')
> 
> I thought that this would print the following when run:
> 
> still here
> uh-oh
> print: nil
> 
> but instead, it printed:
> 
> still here
> print: nil
> 
> Also of note is that if I put this in a file and require that file,
> global assignments cause 'uh-oh' to be printed, as I intended.  Also,
> getfenv(0).print = nil triggers __newindex, as expected.
> 
> I thought that GETGLOBAL/SETGLOBAL was equivalent to operating on
> getfenv(0); I checked the output of luac -l and it is using
> SETGLOBAL.  What do I have wrong?
> 
> Thanks for the help,
> Rob Hoelz

Attachment: signature.asc
Description: PGP signature