2014-02-06 25 views
1

在我的腳本中,我遵循從另一個模塊「導入」函數的做法。所以,我有我的劇本開始類似下面的代碼:在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兩種運行的解決方案)如果你只想要的是什麼utils的模塊的子集

+2

'setmetatable(_G,{__index =需要 「utils的」})' –

+0

葉戈爾的解決方案是好的,只要你只能使用一個模塊。您無法同時使用該解決方案從兩個模塊繼承。 – lhf

+0

在Lua 5.2中,您可以執行'_ENV = require'utils'',所有全局變量將在'utils'中解析。 – lhf

回答

1

,但僅創造當地人,那麼你就不能。其他答案給你整個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'唯一的好處是,它記錄了你模塊會從所需的模塊使用。但它與所有的引號和括號有點吵。

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"}) 
+0

謝謝。爲什麼要求+提取對您而言似乎比單一功能更優雅? (直覺上,我發現它更優雅,但我想聽聽你的想法。) –

+0

我前段時間寫過這篇文章。 [這是我的想法](http://kikito.github.io/blog/2012/03/16/small-functions-are-good-for-the-universe/) – kikito