Recreating setfenv() in Lua 5.2

前端 未结 4 1088
长发绾君心
长发绾君心 2020-12-28 09:44

How can I recreate the functionality of setfenv in Lua 5.2? I\'m having some trouble understanding exactly how you are supposed to use the new _ENV

4条回答
  •  自闭症患者
    2020-12-28 10:06

    To recreate setfenv/getfenv in Lua 5.2 you can do the following:

    if not setfenv then -- Lua 5.2
      -- based on http://lua-users.org/lists/lua-l/2010-06/msg00314.html
      -- this assumes f is a function
      local function findenv(f)
        local level = 1
        repeat
          local name, value = debug.getupvalue(f, level)
          if name == '_ENV' then return level, value end
          level = level + 1
        until name == nil
        return nil end
      getfenv = function (f) return(select(2, findenv(f)) or _G) end
      setfenv = function (f, t)
        local level = findenv(f)
        if level then debug.setupvalue(f, level, t) end
        return f end
    end
    

    RPFeltz's answer (load(string.dump(f)...)) is a clever one and may work for you, but it doesn't deal with functions that have upvalues (other than _ENV).

    There is also compat-env module that implements Lua 5.1 functions in Lua 5.2 and vice versa.

提交回复
热议问题