创建 _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()

而不是打印 "Function is opening file foo.txt" 并再次调用自身的 io.open。 当我替换新环境的函数时,它会编辑旧函数的函数。 我该如何防止这种情况发生?

点赞