更新时间:2023-02-21 09:36:06
从sandbox
内部分配给_ENV
时,您不会覆盖全局环境,而是替换当前正在运行的代码的_ENV
升值.将呼叫添加到print(_ENV)
可能有助于您更好地了解所涉及表的身份.
When you assign to _ENV
from within sandbox
, you're not overwriting the global environment--you're replacing the _ENV
upvalue of the currently running code. Adding calls to print(_ENV)
may help you better understand the identities of the tables involved.
例如:
function print_env()
print(_ENV)
end
function sandbox()
print(_ENV) -- prints: "table: 0x100100610"
-- need to keep access to a few globals:
_ENV = { print = print, print_env = print_env, debug = debug, load = load }
print(_ENV) -- prints: "table: 0x100105140"
print_env() -- prints: "table: 0x100105140"
local code1 = load('print(_ENV)')
code1() -- prints: "table: 0x100100610"
debug.setupvalue(code1, 1, _ENV) -- set our modified env
code1() -- prints: "table: 0x100105140"
local code2 = load('print(_ENV)', nil, nil, _ENV) -- pass 'env' arg
code2() -- prints: "table: 0x100105140"
end
loadin
函数存在于Lua 5.2的某些预发行版本中,但在最终发行版本之前已被删除.相反,Lua 5.2 load
和loadfile
函数接受env
参数.您还可以使用 debug.setupvalue
修改另一个函数的_ENV
.
The loadin
function was present in some pre-release versions of Lua 5.2 but was removed before the final release. Instead, the Lua 5.2 load
and loadfile
functions take an env
argument. You can also modify the _ENV
of another function using debug.setupvalue
.