lua-users home
lua-l archive

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


Hi all!

I need some help in understanding some Lua code Sergey Rhozenko posted a while ago. They are two version of 'setfenv' to use with upcoming Lua 5.2 in order to replace the missing library function. The code is replicated below.


The lines that I don't understand are those where debug.upvaluejoin is called. Why is this call needed? Isn't debug.setupvalue enough?

Any help appreciated


----------------------------------------------------
-- 1st version

setfenv = setfenv or function(f, t)
    f = (type(f) == 'function' and f or debug.getinfo(f + 1, 'f').func)
    local name
    local up = 0
    repeat
        up = up + 1
        name = debug.getupvalue(f, up)
    until name == '_ENV' or name == nil
    if name then
debug.upvaluejoin(f, up, function() return name end, 1) -- use unique upvalue
        debug.setupvalue(f, up, t)
    end
end


-- 2nd version
setfenv = setfenv or function(f, t)
    f = (type(f) == 'function' and f or debug.getinfo(f + 1, 'f').func)
    local name
    local up = 0
    repeat
        up = up + 1
        name = debug.getupvalue(f, up)
    until name == '_ENV' or name == nil
    if name then
debug.upvaluejoin(f, up, function() return t end, 1) -- use unique upvalue, set it to f
    end
end


Thanks in advance.

--
Lorenzo