模組是一個可以使用require
加載的庫,並且只有一個包含表的全局名稱。 模組可以包含許多功能和變數。 所有這些函數和變數都包含在表中,表充當命名空間。 此外,一個良好的模組有必要的子句,以在使用require
語句時返回此表。
Lua模組的特色
模組中表的使用以多種方式,能夠使用與操作任何其他Lua表相同的方式操作模組。 由於能夠操作模組,它提供了其他語言需要特殊機制的額外功能。 由於Lua中模組的這種自由機制,用戶可以通過多種方式調用Lua中的函數。 其中一些操作示例如下所示。
-- Assuming we have a module printFormatter
-- Also printFormatter has a funtion simpleFormat(arg)
-- Method 1
require "printFormatter"
printFormatter.simpleFormat("test")
-- Method 2
local formatter = require "printFormatter"
formatter.simpleFormat("test")
-- Method 3
require "printFormatter"
local formatterFunction = printFormatter.simpleFormat
formatterFunction("test")
在上面的示例代碼中,可以看到Lua中的編程靈活性,沒有任何特殊的附加代碼。
require函數
Lua提供了一個名為require
的高級函數來加載所有必需的模組。 它保持盡可能簡單,以避免有太多關於模組的資訊來加載。 require
函數只是將模組假定為一塊代碼,它定義了一些值,實際上是包含函數或表。
示例
考慮一個簡單的例子,其中一個函數是數學函數。 將此模組稱為mymath
,檔案名為mymath.lua
。 檔的代碼內容如下 -
local mymath = {}
function mymath.add(a,b)
print(a+b)
end
function mymath.sub(a,b)
print(a-b)
end
function mymath.mul(a,b)
print(a*b)
end
function mymath.div(a,b)
print(a/b)
end
return mymath
現在,為了在另一個檔(例如,moduletutorial.lua
)中訪問此Lua模組,需要使用以下代碼段。
mymathmodule = require("mymath")
mymathmodule.add(10,20)
mymathmodule.sub(30,20)
mymathmodule.mul(10,20)
mymathmodule.div(30,20)
要運行此代碼,需要將兩個Lua檔放在同一目錄中,或者,可以將模組檔放在包路徑中,它需要額外的設置。 當運行上面的程式時,將得到以下輸出 -
30
10
200
1.5
注意事項
- 將運行的模組和文件放在同一目錄中。
- 模組名稱及其檔案名應相同。
- 使用
require
函數返回模組,因此模組最好如上所示實現,儘管可以在其他地方找到其他類型的實現。
實現模組的舊方法
下麵將以舊方式重寫上面相同的示例,它使用package.seeall
類型的實現。 這在Lua版本5.1
和5.0
中使用。 mymath
模組如下所示。
module("mymath", package.seeall)
function mymath.add(a,b)
print(a+b)
end
function mymath.sub(a,b)
print(a-b)
end
function mymath.mul(a,b)
print(a*b)
end
function mymath.div(a,b)
print(a/b)
end
moduletutorial.lua 中模組的用法如下所示 -
require("mymath")
mymath.add(10,20)
mymath.sub(30,20)
mymath.mul(10,20)
mymath.div(30,20)
當運行上面的操作時,將獲得相同的輸出。 但建議使用較舊版本的代碼,並假設它不太安全。 許多使用Lua進行編程的SDK如Corona SDK都不推薦使用它。