lua-users home
lua-l archive

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


On Fri, Jan 22, 2010 at 9:20 AM, M Joonas Pihlaja
<jpihlaja@cc.helsinki.fi> wrote:
> I suppose you'll need debug.getfenv() for that, no?  If you need to
> keep track of the current env yourself explicitly (say by
> side-effecting some state which you need to undo) then I'm not sure
> how it would work.

Yes. Have a look at this:

function global(env)
 local outer = _G --> !
 return setmetatable({},{
   __index = function(tab, key)
       if env[key] ~= nil then return env[key] end -- look in our environment
       if outer[key] ~= nil then return outer[key] end -- if not, look
in enclosing environment
       return nil
 end;
 __newindex = function(tab, key, val)
      env[key] = val
 end
 })
end

t = {}

in global(t) do
    x = 10
    y = x*x
    z = math.max(10,y)
end

print(t.x,t.y,t.z)

Works as expected if we just want global access. But the temptation to
use getfenv(1) otherwise is pretty strong ;)

steve d.