如何在Lua库中构建内部依赖项?

时间:2013-04-13 15:02:02

标签: lua

我正在努力弄清楚如何构建然后在我正在编写的Lua库中使用内部依赖项。

我已经像这样定义了我的库:

./alib.lua
./alib/adependency.lua

代码:

-- File: ./alib.lua
local ad = require "alib.adependency"
module( "alib")
return {}

-- File: ./alib/adependency.lua
module( "adependency" )
return {}

这是一种享受:

$ lua alib.lua
<no output>

现在让我们将这个库“添加”到另一个应用程序中:

./anapp.lua
./lib/alib.lua
./lib/alib/adependency.lua

新代码:

-- File: ./anapp.lua
local alib = require "lib.alib"
local print = print
module( "anapp")
print "Hello"

尝试运行它:

$ lua anapp.lua
lua: ./lib/alib.lua:2: module 'alib.adependency' not found:
    no field package.preload['alib.adependency']
    no file './alib/adependency.lua'
    no file '/usr/local/share/lua/5.1/alib/adependency.lua'
    no file '/usr/local/share/lua/5.1/alib/adependency/init.lua'
    no file '/usr/local/lib/lua/5.1/alib/adependency.lua'
    no file '/usr/local/lib/lua/5.1/alib/adependency/init.lua'
    no file '/usr/share/lua/5.1/alib/adependency.lua'
    no file '/usr/share/lua/5.1/alib/adependency/init.lua'
    no file './alib/adependency.so'
    no file '/usr/local/lib/lua/5.1/alib/adependency.so'
    no file '/usr/lib/x86_64-linux-gnu/lua/5.1/alib/adependency.so'
    no file '/usr/lib/lua/5.1/alib/adependency.so'
    no file '/usr/local/lib/lua/5.1/loadall.so'
    no file './alib.so'
    no file '/usr/local/lib/lua/5.1/alib.so'
    no file '/usr/lib/x86_64-linux-gnu/lua/5.1/alib.so'
    no file '/usr/lib/lua/5.1/alib.so'
    no file '/usr/local/lib/lua/5.1/loadall.so'
stack traceback:
    [C]: in function 'require'
    ./lib/alib.lua:2: in main chunk
    [C]: in function 'require'
    anapp.lua:2: in main chunk
    [C]: ?
亲爱的,亲爱的。现在我在库中进行手动编辑:

-- File: ./lib/alib.lua
-- local ad = require "alib.adependency" -- Doesn't work
local ad = require "lib.alib.adependency" -- Works
module( "alib")
return {}

它有效:

$ lua anapp.lua
Hello

似乎Lua的require()与Lua运行的最终脚本相关的路径,而不是调用require()的脚本。

每次在项目中添加一个Lua库时,你不必手动修复内部路径require() d ...而且我不知道这是如何从一个单元中工作的测试视角。我做错了什么?

1 个答案:

答案 0 :(得分:2)

我认为最干净的解决方案是保留您的库,然后让任何人使用负责正确配置package.path的库。在您的设置中,这意味着应用程序应将lib文件夹添加到路径:

package.path = './lib/?.lua;' .. package.path

有关路径的详情,请参阅Is there a better way to require file from relative path in lua等相关问题以及the manual