lua-users home
lua-l archive

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


> getfenv (f)
>
> Returns the current environment in use by the function. f can be a Lua
> function or a number that specifies the function at that stack level:
> Level 1 is the function calling getfenv. If the given function is not a
> Lua function, or if f is 0, getfenv returns the global environment. The
> default for f is 1.
>
> http://www.lua.org/manual/5.1/manual.html#pdf-getfenv

Oh, I've misread the manual, sorry -- missed the f parameter somehow. :(

Yes, this works:

in_context_of = function(t)
  assert_is_table(t)
  return function(func)
    assert_is_function(func)
    local e = getfenv(func)
    setfenv(func, t)
    return func(), setfenv(func, e)
  end
end

p = function() print("global") end
f = function() p() end
t1 = { p = function() print("t1") end }
t2 = { p = function() print("t2") end }
setfenv(f, t1)
f()
in_context_of(t2)(f)
f()
-- Prints
-- t1
-- t2
-- t1

Alexander.