[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Get environment of a function
- From: "Alexander Gladysh" <agladysh@...>
- Date: Fri, 17 Mar 2006 18:28:20 +0300
Hi all!
Lua 5.0.2.
I'm trying to implement function "in_context_of", allowing user to
execute arbitrary function using given table as environment for that
call only. (Thanks to PA and Jerome Vuarand for suggesting ways to do
it.)
In so far I've got:
in_context_of = function(t)
assert_is_table(t)
return function(func)
setfenv(func, t)
return func(), setfenv(func, _G) -- Assuming setfenv returns nil.
end
end
-- Usage example:
p = function() return "in _G" end
t = { p = function() return "in t" end }
f = function() return p() end
print(in_context_of(t)(f))
print(f())
-- Prints
-- in t
-- in _G
But now in_context_of resets environment of passed function to _G. Is
there a way to avoid this? The getfenv() works only for current
function. :(
BTW, how cheap are setfenv/getfenv calls?
Thanks in advance,
Alexander.
P.S. Just in case:
assert_is_table = function(val, msg)
assert(type(val) == "table", msg)
return val
end