[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: changing global environments
- From: Graham Wakefield <lists@...>
- Date: Sat, 24 Mar 2007 15:23:16 -0700
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