我最近帮助开发了Torch的Dataframe包。由于代码库已快速翻倍,因此需要将类拆分为多个部分,以便更好地进行组织和跟进(issue #8)。
一个简单的测试类将是测试包的根文件夹中的 test.lua 文件:
test = torch.class('test')
function test:__init()
self.data = {}
end
function test:a()
print("a")
end
function test:b()
print("b")
end
现在,对于这种情况,只需要:
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"] = 'test.lua',
}
}
答案 0 :(得分:0)
为了让多个文件适用于单个类,必须返回最初创建的类对象并将其传递给子部分。上面的例子可以放在文件结构中:
\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
文件。以下可能有点过于复杂,但需要注意:
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
我希望如果您遇到同样的问题并且发现文档有点过于稀疏,这会有所帮助。如果您碰巧知道更好的解决方案,请分享。