lua-users home
lua-l archive

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


Like others I have found the setfenv/getfenv to be a very useful feature of
Lua.  I use the feature primarily to limit variables in a function from
becoming global variables and to set default values in the environment that
can then be changed by a getfenv() call later.

In the new 2.0 Lua I find that I can still use about the same programming
style by defining getfenv() and setfenv() functions as in the example below.
A table of environments is maintained in _G._ENV.  The addition to a
function definition is then the "in getfenv(f) do --- end" construct.

I still hope the authors will keep the old setfenv/getfenv

getfenv = function(fn)
	for em,val in pairs(_G._ENV) do
		if en==fn then return val end 
	end
end
setfenv = function(fn,tbl)
	if _G._ENV==nil then _G._ENV = {} end --environment table
	_G._ENV[fn]=tbl
end

f = function() in getfenv(f) do -- new in --- do 
	-------
	print('NMAX =',NMAX)
	------
end end -- double end, which I don't like
setfenv(f,{NMAX = 100,print=print}) -- set environment, NMAX known only
within f

f()-- prints NMAX = 100
getfenv(f).NMAX = 200 -- change environment
f() -- prints NMAX = 200