Recreating setfenv() in Lua 5.2

前端 未结 4 1090
长发绾君心
长发绾君心 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:26

    It's a bit expensive, but if it's that important to you...

    Why not use string.dump, and re-load the function into the right environment?

    function setfenv(f, env)
        return load(string.dump(f), nil, nil, env)
    end
    function foo()
        herp(derp)
    end
    
    setfenv(foo, {herp = print, derp = "Hello, world!"})()
    

提交回复
热议问题