Lua环境与模块

假设我有一个模块:

-- env.lua

local env = {}

function env.resolve(str)
  print("mod", _ENV)

  if _resolve_path ~= nil then
    return _resolve_path(str)
  else
    error("bad env")
  end
end

return env

还有一些使用它的代码:

-- 沙盒演示
-- 运行方式:lua env-test.lua

env = require('env')

function _resolve_path(path)
  return "/" .. path
end

print("在 main() 之前")
print("", _ENV)
print("", env.resolve("test"))

local sandbox
do
  local _ENV = {
    print = print,
    env = env,
    _resolve_path = function (path)
      return "/chroot/" .. path
    end
  }
  function sandbox()
    print("来自 sandbox()")
    print("", _ENV)
    print("", env.resolve("test"))
  end
end

sandbox()

print("在 main() 之后")
print("", _ENV)
print("", env.resolve("test"))

我想实现的是,从sandbox()中的env.resolve()使用环境中自定义的\_resolve\_path函数。但从沙盒函数调用的代码中似乎未应用环境。目标是根据调用它们的位置来改变某些模块的行为,例如使用具有不同本地\_resolve\_path()函数的sandbox{1,2,3}()

点赞
用户415823
用户415823

当你使用 require 加载你的模块时,它会绑定到全局环境。一旦函数在某个环境中创建,它在整个生命周期中都会有该环境。

在 Lua 5.2 之前,你可以使用 set/getfenv 来更改环境,但现在的环境是词法作用域的。只能通过调试库通过更改 _ENV upvalue 来更改环境。

那么,如何在不同的环境中运行相同的函数?你可以将环境作为参数传递:

function env.resolve(str, _ENV)
  print("mod", _ENV)
  if _resolve_path ~= nil then
    return _resolve_path(str)
  else
    error("bad env")
  end
end

然后像这样调用 resolve

env.resolve('test', _ENV)

或者,如果你希望每次调用 resolve 都无需指定环境,你可以将 resolve 函数绑定到每个新环境:

-- env.lua
local print = print
local error = error
local env = {}

-- this is the actual resolve function that takes the environment as a parameter
local function resolve_env(str, _ENV)
  print("mod", _ENV)
  if _resolve_path ~= nil then
    return _resolve_path(str)
  else
    error("bad env")
  end
end

-- this is the module (ie. global) resolve
function env.resolve(str)
  return resolve_env(str, _ENV)
end

-- this function binds a resolve function to a sandbox environment
function env.bind(_ENV)
  _ENV.env = {
    resolve = function(str)
      return resolve_env(str, _ENV)
    end
  }
  return _ENV
end

return env

现在,沙盒可以设置绑定的解析函数:

-- sandbox.lua
env = require 'env'

function _resolve_path(path)
  return "/" .. path
end

print("before main()")
print("", _ENV)
print("", env.resolve("test"))

local sandbox; do
  local _ENV = env.bind{
    print = print,
    _resolve_path = function (path)
      return "/chroot/" .. path
    end
  }

  function sandbox()
    print("from sandbox()")
    print("", _ENV)
    print("", env.resolve("test"))
  end
end

sandbox()

print("after main()")
print("", _ENV)
print("", env.resolve("test"))

这将产生以下结果:

$ lua sandbox.lua
before main()
        table: 00612f40
mod     table: 00612f40
        /test
from sandbox()
        table: 0061c7a8
mod     table: 0061c7a8
        /chroot/test
after main()
        table: 00612f40
mod     table: 00612f40
        /test
2016-08-30 18:04:58