lua-users home
lua-l archive

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


Specifically, why does this not work:

id = 0
env1 = { id = 1, __index = _G }
setmetatable(env1, env1)

function subtest()
print("subtest", id)
b = id
end

function test()
print("test", id)
subtest()
a = id
end

test()
setfenv(0, env1) -- change global environment
test() -- environment in test & subtest remains unchanged

output:
test 0
subtest 0
test 0
subtest 0

What I want is some way to change the environment of ALL existing and future functions that do not have a specific environment already set.  Perhaps I need to have a 'virtual' environment at the root, whose __index and __newindex can be remapped dynamically?

This is only speculative, it might not be a good idea at all, but I'm looking ahead to coroutines as a way to be able to switch system data state quickly and independently of system functional behavior, and it seemed (until I noticed this) that environments would be a good way to do it.



On Mar 24, 2007, at 3:23 PM, Graham Wakefield wrote:

Hi,

Is there any way to set the environment of a function such that all functions it calls will also inherit this environment?  In the example below, I change the environment of fmain, which in turn calls fsub, but the environment of fsub is unchanged.

I also tried changing the environment in fmain using setfenv(1, e) but it still doesn't affect fsub.  Setting the global environment via setfenv(0, e) affects everything in the program. Would changing the environment via C (LUA_GLOBALSINDEX perhaps?) achieve what I want, or is that the equivalent of setfenv(0)?  Basically, is it possible for a function to have the environment dynamically bound, or is it fixed at creation/setfenv time?

fsub = function()
print("fsub", getfenv(0), getfenv(1))
b = 1
end

fmain = function()
print("fmain", getfenv(0), getfenv(1))
a = 1
fsub()
end

e = { __index = getfenv(0) }
setmetatable(e, e)

setfenv(fmain, e)

fmain()

print(a, b)
print(e.a, e.b)

outputs:
fmain table: 0x1452a450 table: 0x1452f010
fsub table: 0x1452a450 table: 0x1452a450
nil 1
1 1






Grrr Waaa
www.grahamwakefield.net