1
我正在努力弄清楚如何在我正在寫的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 ......並且我不明白從單元測試的角度來看它是如何工作的。我究竟做錯了什麼?
是;或者,將lib安裝在Lua默認路徑的目錄中,如'/ usr/local/share/lua/5.1 /' –