为什么在由 load() 编译的另一个函数中调用的函数的 _ENV 与提供给 load() 的环境不同?

问题描述 投票:0回答:0

Lua 5.4.4

当我从 Lua 块

is_env_g()
内部调用函数
f
时,它是使用
load()
从字符串编译而来的,它具有为
load()
env
参数提供的不同环境,
is_env_g()
函数不会不要使用
env
参数作为它的
_ENV
.

遵守以下代码:

-- create a new table with the parent's variables available via the __index metakey
function new_env(parent)
  return setmetatable({}, {
    __index = parent
  })
end

function run_lua_string(luastr, env)
  local f = load(luastr,  '', 't', env) -- compile luastr using env as the first upvalue (_ENV)
  f()                                   -- run the compiled luastr
end

function is_env_g()
  print(_ENV == _G)
end

local luastr = 
[[
  print(_ENV == _G) -- prints 'false' as expected
  is_env_g()        -- I expect 'false' but receive 'true' - why?
]]

-- prepare a new env; this one "inherits" from _ENV, which in this case is also _G, but it is *not* equal to _G
local env = new_env(_ENV)

-- compile and run luastr in the env we created above
run_lua_string(luastr, env)

当我用

luastr
编译和运行 Lua 代码字符串
run_lua_string
时,
print(_ENV == _G)
内的
luastr
行按预期打印
true
。但是,当同一行 (
print(_ENV == _G)
) 在另一个函数
is_env_g()
中运行时,它本身是从已编译的
luastr
块中调用的,我收到
false
.

似乎

is_env_g()
函数没有提供给
env
load()
arg作为它的
_ENV
上值-这是为什么?

如何修改,以便

is_env_g()
使用提供给
_ENV
load()
论点的
env
?我知道我们可以修改它以显式传递
luastr
_ENV
像这样:

function is_env_g(env)
  print(env == _G)
end

local luastr = 
[[
  is_env_g(_ENV)
]]

有没有另一种方法不通过

_ENV
作为这样的论点?

lua environment
© www.soinside.com 2019 - 2024. All rights reserved.