模块就像可以使用 require 加载的库,并且具有包含Table的单个全局名称,该模块可以包含许多函数和变量。

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")

让无涯教程考虑一个简单的示例,其中一个函数具有数学函数。将此模块称为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

旧方法实现

现在以较旧的方式重写相同的示例,该示例使用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)已弃用此方法。

参考链接

https://www.learnfk.com/lua/lua-modules.html