lua-users home
lua-l archive

Re: Lua 5.2 - emulation of old setfenv

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


Peter Cawley wrote:
_ENV is always the first upvalue of a chunk (i.e. a function created
by passing a piece of non-bytecode source code to lua_load), but this
is not true for functions in general. Functions in general may or may
not have an upvalue called _ENV, which may or may not be a shared
upvalue, and if they do have an _ENV upvalue, it doesn't have to be
the 1st upvalue.
Thanks! This clarifies why my attempt didn't work!
The specific use case I'm trying to tackle is the following (simplified):
----------------------------------------------
local function Runner(func)
local env = {}
-- env is populated here with entries, e.g.:
env.Log = function(msg)
 -- store away the message
end
-- ...
local oldenv = getfenv(func)
-- set a metatable so that oldenv is still
-- visible, but entries in env "override" those
-- in oldenv
setmetatable( env, { __index = oldenv } )
setfenv(func, env)
func()
-- here env is used with
-- any possible modification done
-- by running func
-- ...
end
Then Runner is called like this:
Runner( function()
 -- anonymous function which performs some task
 -- using the facilities provided by "Runner", e.g.:
 Log 'initializing the transmogryfier...'
 -- ...
end)
----------------------------------------------------
So I hope there is a way to replace setfenv/getfenv easily in 5.2 (at least for this use case), otherwise I have to rewrite those scripts in a different way.
--
Lorenzo

AltStyle によって変換されたページ (->オリジナル) /