我正在努力弄清楚如何在我正在编写的 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 库时,您都不必手动修复 Lua 库中的内部路径require()
d ......而且从单元测试的角度来看,我也不知道这是如何工作的。我究竟做错了什么?