lua-users home
lua-l archive

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


Cool. Now, since setfenv is totally possible, I like the _ENV :)

Here are my implementations of setfenv and getfenv:

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

getfenv = getfenv or function(f)
    f = (type(f) == 'function' and f or debug.getinfo(f + 1, 'f').func)
    local name, val
    local up = 0
    repeat
        up = up + 1
        name, val = debug.getupvalue(f, up)
    until name == '_ENV' or name == nil
    return val
end

On 16.06.2010 18:46, Roberto Ierusalimschy wrote:
I thought upvaluejoin can only join upvalues. How can it be used to
break the link?
function breaklink (f, upidx)
   local a
   local function dummy () return a end
   debug.upvaluejoin(f, upidx, dummy, 1)
end

The call 'breaklink(f,n)' will make the n-th upvalue from 'f' point to
a fresh upvalue (refering to variable 'a'), not shared with any other
function.

-- Roberto




--

___________________________________________
Best regards,
Sergey Rozhenko                 mailto:sergroj@mail.ru