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:
fmaintable: 0x1452a450table: 0x1452f010
fsubtable: 0x1452a450table: 0x1452a450
nil1
11