Recreating setfenv() in Lua 5.2

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

    In Lua5.2 a sandboxeable function needs to specify that itself. One simple pattern you can use is have it receive _ENV as an argument

    function(_ENV)
        ...
    end
    

    Or wrap it inside something that defines the env

    local mk_func(_ENV)
        return function()
            ...
        end
    end
    
    local f = mk_func({print = print})
    

    However, this explicit use of _ENV is less useful for sandboxing, since you can't always assume the other function will cooperate by having an _ENV variable. In that case, it depends on what you do. If you just want to load code from some other file then functions such as load and loadfile usually receive an optional environment parameter that you can use for sandboxing. Additionally, if the code you are trying to load is in string format you can use string manipulation to add _ENV variables yourself (say, by wrapping a function with an env parameter around it)

    local code = 'return function(_ENV) return ' .. their_code .. 'end'
    

    Finally, if you really need dynamic function environment manipulation, you can use the debug library to change the function's internal upvalue for _ENV. While using the debug library is not usually encouraged, I think it is acceptable if all the other alternatives didn't apply (I feel that in this case changing the function's environment is deep voodoo magic already so using the debug library is not much worse)

提交回复
热议问题