在Lua中导入一堆名称

时间:2014-02-06 11:58:26

标签: lua

在我的脚本中,我遵循从另一个模块“导入”功能的做法。所以我在脚本开头有类似下面的代码:

local some_function = assert(require("utils").some_function)
local another_func = assert(require("utils").another_func)
local yet_another = assert(require("utils").yet_another)
local and_another = assert(require("utils").and_another)

但是这段代码不太可读。

assert()用于防止函数名称中的拼写错误。)

我知道我可以轻松编写自己的函数,比如require_names(),然后将上面的代码转换为:

local some_function, another_func, yet_another, and_another
  = require_names("utils", { "some_function", "another_func", "yet_another", "and_another" })

这看起来很多更好。尽管如此,它并不是最优的:此代码中存在冗余:函数名称重复两次。

我有没有办法写我的require_names()以便它没有冗余问题?

或者,您对以其他方式解决可读性问题有什么想法吗?

(我需要在Lua 5.1和5.2上运行的解决方案)

2 个答案:

答案 0 :(得分:1)

如果您只想要utils模块中的一部分,但只创建本地,那么您不能。其他答案为您提供了整个utils模块,在这种情况下,我不明白为什么不使用require 'yourmodule'。如果你可以放弃当地人,那么:

function require_names(modName, objNames)
    for i,v in ipairs(objNames)  do
         _G[v] = assert(require(modName)[v]) 
    end
end

适用于5.1:

> print(setn)
nil
> print(insert)
nil
> require_names("table", {"setn", "insert"})
> print(setn)
function: 005F7910
> print(insert)
function: 005F7890

唯一的非全局变量选项是将您想要的内容放在本地表中,以获得您需要的子集:

function require_names(modName, objNames)
    local mod = {}
    for i,v in ipairs(objNames) do
         mod[v] = assert(require(modName)[v]) 
    end
    return mod
end

local utils = require_names("utils", { 'a', 'b' })
utils.a = asdfasf
print(utils.b)

但是,与local utils=require 'utils'相比,上述唯一的好处是它会记录您要从所需模块中使用的模块。但是所有的引号和括号都有点吵。

答案 1 :(得分:0)

我会这样做:

local u = require 'utils'

然后像这样使用它:

u.some_function(...)

这很容易打字,非常明显。

如果您真的需要本地人,那么我不会使用名为require_names的单个函数,而是使用两个:常规require + extract。这是extract

local function extract(t, keys)
  local values = {}
  for i=1, #keys do values[i] = t[keys[i]] end
  return unpack(values)
end

用法:

local utils = require 'utils'
local some_function, another_func, yet_another, and_another = 
  extract(utils, { "some_function", "another_function", "yet_another", "and_another"})