lua-users home
lua-l archive

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


On 21 May 2010 11:55, François Perrad <francois.perrad@gadz.org> wrote:
I rewrite setfenv as follow :

local function setfenv (level, M)
    level = level + 1
    local func = debug.getinfo(level, 'f').func
    local up = 1
    while true do
        local name = debug.getupvalue(func, up)
        if name == '_ENV' then
            debug.setupvalue(func, up, M)
            return
        end
        if name == nil then
            break
        end
        up = up + 1
    end
    _G.setfenv(level, M) -- Lua 5.1
end

François

Does this run into the problem that Roberto points out with shared upvalues?

local print = print
x = 1
function foo ()
  local function a()
    print(x)
  end
  local function b()
    print(x)
  end
  return a, b
end

a, b = foo()
setfenv(a, {x=2})
b()

Does that print 1 or 2?

    henk