为了让多个文件为单个类工作,有必要返回最初创建的类对象并将其传递给小节。上面的例子可以放入文件结构中:
\init.lua
\main.lua
\test-0.1-1.rockspec
\Extensions\a.lua
\Extensions\b.lua
根据luarocks install/make
'require' 语法复制文件,其中每个.
表示一个目录,而.lua
则省略,即我们需要将 rockspec 更改为:
package = "torch-test"
version = "0.1-1"
source = {
url = "..."
}
description = {
summary = "A test class",
detailed = [[
Just an example
]],
license = "MIT/X11",
maintainer = "Jon Doe"
}
dependencies = {
"lua ~> 5.1",
"torch >= 7.0",
}
build = {
type = 'builtin',
modules = {
["test.init"] = 'init.lua',
["test.main"] = 'main.lua',
["test.Extensions.a"] = 'a.lua',
["test.Extensions.b"] = 'b.lua'
}
}
因此,上面将创建一个test文件夹,其中包与文件和子目录一起驻留。类初始化现在驻留在init.lua
返回类对象的 中:
test = torch.class('test')
function test:__init()
self.data = {}
end
return test
子类文件现在需要拾取使用传递的类对象loadfile()
(参见init.lua
下面的文件)。现在a.lua
应该如下所示:
local params = {...}
local test = params[1]
function test:a()
print("a")
end
和类似的补充b.lua
:
local params = {...}
local test = params[1]
function test:b()
print("b")
end
为了将所有内容粘合在一起,我们拥有该init.lua
文件。以下可能有点过于复杂,但它照顾:
- 找到所有可用的扩展并加载它们(注意:需要你应该添加到rockspec的lua文件系统,你仍然需要将每个文件添加到rockspec中,否则它不会在Extensions文件夹中)
- 标识路径文件夹
- 加载 main.lua
- 在没有安装包的纯测试环境中工作
代码init.lua
:
require 'lfs'
local file_exists = function(name)
local f=io.open(name,"r")
if f~=nil then io.close(f) return true else return false end
end
-- If we're in development mode the default path should be the current
local test_path = "./?.lua"
local search_4_file = "Extensions/load_batch"
if (not file_exists(string.gsub(test_path, "?", search_4_file))) then
-- split all paths according to ;
for path in string.gmatch(package.path, "[^;]+;") do
-- remove trailing ;
path = string.sub(path, 1, string.len(path) - 1)
if (file_exists(string.gsub(path, "?", "test/" .. search_4_file))) then
test_path = string.gsub(path, "?", "test/?")
break;
end
end
if (test_path == nil) then
error("Can't find package files in search path: " .. tostring(package.path))
end
end
local main_file = string.gsub(test_path,"?", "main")
local test = assert(loadfile(main_file))()
-- Load all extensions, i.e. .lua files in Extensions directory
ext_path = string.gsub(test_path, "[^/]+$", "") .. "Extensions/"
for extension_file,_ in lfs.dir (ext_path) do
if (string.match(extension_file, "[.]lua$")) then
local file = ext_path .. extension_file
assert(loadfile(file))(test)
end
end
return test
如果您遇到同样的问题并且发现文档过于稀疏,我希望这会有所帮助。如果您碰巧知道更好的解决方案,请分享。