【发布时间】:2013-04-04 15:15:24
【问题描述】:
我想创建一个在不同文件夹中有多个模块的程序。主程序将确定需要加载哪个模块并将其加载。除此之外它还会加载一些核心功能。
我创建了这个逻辑的原型,效果很好。 但由于我是 Lua 的新手,我不确定实现此功能的正确方法。
现在我有下一个文件结构:
aoc(主程序):
aoc = {}
aoc_base_path = debug.getinfo(1).source:match("@(.*)/.*$") -- base path to my program
if not aoc_base_path then
aoc_base_path = ''
else
aoc_base_path = aoc_base_path..'/'
end
local aoc_base_arg={...}
dofile(aoc_base_path.."core/core")
local module = assert(loadfile(aoc_base_path.."modules/"..aoc_base_arg[1].."/module"))
local arg = table.copy(aoc_base_arg) -- this is my custom function (I'm not provide you with listing, it just copy one table to another one
table.remove(arg,1)
module(arg,aoc) -- pass to module all arguments except first one
core/core(核心函数加载器):
dofile (aoc_base_path..'core/move')
核心/移动:
local function move(direction, refuel, dig, attack)
-- some logic in local function (to not be overwriten in module)
end
function aoc.move()
-- global function (it logic can be changed by module in case it needed)
return move()
end
modules/mine/module(模块):
local arg={...} -- I passed 2 arguments in aoc main program
arg = arg[1]
local aoc = arg[2]
aoc.move()
暂时
lua> aoc 我的
或
lua> path/to/aoc mine
工作正常。但是,如果我做错了什么,谁能指出我?
编辑:通过获取aoc_base_path改变逻辑
【问题讨论】:
-
您可能还想稍微调整一下 package_path 。也许这样会更好。
-
@BartekBanachewicz 如果您的意思是与
debug.getinfo(1).source:match("@(.*)/.*$")一致,这只是一个示例。实际上,我以某种不同的方式获得了这条路径(我的程序是一些游戏的模组,它为我提供了shell.getRunningProgram()功能)。 -
是错字吗:
match("@(.*)/.*$")?可能,提到了match'^(.*)/'?也可以写成match'(.*)/'。 -
@EgorSkriptunoff nope:
echo 'print(debug.getinfo(1).source)' > test; lua test给了@test -
@ArthurHalma - 感谢您提供信息。以前从未使用过此功能。