【发布时间】:2012-12-26 18:21:36
【问题描述】:
如何在 Lua 5.2 中重新创建 setfenv 的功能?我无法准确理解您应该如何使用新的 _ENV 环境变量。
在 Lua 5.1 中,您可以使用 setfenv 轻松地对任何函数进行沙箱处理。
--# Lua 5.1
print('_G', _G) -- address of _G
local foo = function()
print('env', _G) -- address of sandbox _G
bar = 1
end
-- create a simple sandbox
local env = { print = print }
env._G = env
-- set the environment and call the function
setfenv(foo, env)
foo()
-- we should have global in our environment table but not in _G
print(bar, env.bar)
运行此示例会显示输出:
_G table: 0x62d6b0
env table: 0x635d00
nil 1
我想在 Lua 5.2 中重新创建这个简单的例子。下面是我的尝试,但它不像上面的例子那样工作。
--# Lua 5.2
local function setfenv(f, env)
local _ENV = env or {} -- create the _ENV upvalue
return function(...)
print('upvalue', _ENV) -- address of _ENV upvalue
return f(...)
end
end
local foo = function()
print('_ENV', _ENV) -- address of function _ENV
bar = 1
end
-- create a simple sandbox
local env = { print = print }
env._G = env
-- set the environment and call the function
foo_env = setfenv(foo, env)
foo_env()
-- we should have global in our envoirnment table but not in _G
print(bar, env.bar)
运行此示例会显示输出:
upvalue table: 0x637e90
_ENV table: 0x6305f0
1 nil
我知道有关此主题的其他几个问题,但它们似乎主要处理加载动态代码(文件或字符串),这些代码使用 Lua 5.2 中提供的新 load 函数运行良好。在这里,我特别要求在沙箱中运行任意函数的解决方案。我想在不使用 debug 库的情况下执行此操作。根据 Lua documentation,我们不应该依赖它。
【问题讨论】:
标签: lua