一次导入多个lua文件? [英] Import multiple lua files at once?
问题描述
如何在另一个lua文件中导入多个lua文件并使用它们.我正在使用
How do I import multiple lua files in another lua file and use them. I am using
dofile("/some/paht/file.lua")
.一次导入多个lua文件的最佳方法是什么?如果我错了,请纠正我.
for each and every file. What is the best way to import multiple lua files at once? Correct me if I am wrong.
推荐答案
您可以使用 package.path .
You can use require to load modules. Using dofile
works, but require
will cache the loaded module, and you can control where to look for modules via package.path.
您可以通过为每个模块调用require
来加载多个模块.
You can load multiple modules by just calling require
for each one.
require 'file1' --> load ./file1.lua
require 'file2' --> load ./file2.lua
如果您需要从默认路径以外的地方加载模块,则可以在调用require之前更新package.path
:
If you need to load a module from somewhere not in the default path you can update package.path
before calling require:
package.path = '/some/path/?.lua;'..package.path
如果模块具有Lua模块常见的返回值(例如函数表),则将变量设置为返回值require
.
If your modules have a return value (ex. a table of functions), which is common for Lua modules, then set a variable to the return value of require
.
local file1 = require 'file1' --> load file1.lua
local file2 = require 'file2'
如果要一次加载多个文件,请执行以下操作:创建一个使用模块名称表的函数,每个模块都需要一个,然后全部返回.
If you want to load multiple files in one go; create a function that takes a table of module names, requires each one, and then returns them all.
local function import(t)
for i, v in ipairs(t) do
t[i] = require(v)
end
return table.unpack(t)
end
local file1, file2 = import{'file1', 'file2'}
这篇关于一次导入多个lua文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!