在我的腳本中,我遵循從另一個模塊「導入」函數的做法。所以,我有我的劇本開始類似下面的代碼:在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的模塊的子集
'setmetatable(_G,{__index =需要 「utils的」})' –
葉戈爾的解決方案是好的,只要你只能使用一個模塊。您無法同時使用該解決方案從兩個模塊繼承。 – lhf
在Lua 5.2中,您可以執行'_ENV = require'utils'',所有全局變量將在'utils'中解析。 – lhf