Lua - Modules(模块)

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

模块就像可以使用 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中模块的用法。

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

来源:LearnFk无涯教程网

require("mymath")
mymath.add(10,20)
mymath.sub(30,20)
mymath.mul(10,20)
mymath.div(30,20)

运行上面的命令时,将获得相同的输出。许多使用Lua进行编程的SDK(如Corona SDK)已弃用此方法。

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

技术教程推荐

接口测试入门课 -〔陈磊〕

检索技术核心20讲 -〔陈东〕

正则表达式入门课 -〔涂伟忠〕

WebAssembly入门课 -〔于航〕

技术面试官识人手册 -〔熊燚(四火)〕

容量保障核心技术与实战 -〔吴骏龙〕

Redis源码剖析与实战 -〔蒋德钧〕

网络排查案例课 -〔杨胜辉〕

AI大模型系统实战 -〔Tyler〕

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