LuaModules(模块)

LuaModules(模块) 首页 / Lua入门教程 / LuaModules(模块)

模块就像可以使用 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文件放置在同一目录中,或者可以将模块文件放置在包路径中。当运行上面的程序时,将得到以下输出。

链接:https://www.learnfk.comhttps://www.learnfk.com/lua/lua-modules.html

来源:LearnFk无涯教程网

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)已弃用此方法。

祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

教程推荐

重学TypeScript -〔周爱民〕

JavaScript进阶实战课 -〔石川〕

Web漏洞挖掘实战 -〔王昊天〕

Python自动化办公实战课 -〔尹会生〕

WebAssembly入门课 -〔于航〕

如何看懂一幅画 -〔罗桂霞〕

.NET Core开发实战 -〔肖伟宇〕

深入剖析Kubernetes -〔张磊〕

深入浅出gRPC -〔李林锋〕

好记忆不如烂笔头。留下您的足迹吧 :)