lua - 创建 _ENV 的深层副本并更改值而不更改原件
问题描述
我正在研究一些 Lua 代码,它可以将函数调用作为自定义环境进行沙箱化。我需要创建 _ENV 的副本,修改其中的函数,并使用新环境运行函数。到目前为止,我有这个:
new_env = _ENV
function newIoOpen(f,m)
print("Function is opening file "..f)
return io.open(f,m)
end
new_env.io.open = newIoOpen
function testFunction()
io.open("bar.txt","r") -- should print: "Function is opening file bar.txt"
end
io.open("foo.txt","r") -- should stay silent
setfenv(testFunction,new_env)
testFunction()
相反,常规 io.open 调用会打印“函数正在打开文件 foo.txt”并再次调用自身。与函数的 io.open 相同。当我替换新环境的功能时,它会编辑旧环境。我怎样才能防止这种情况发生?