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

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

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

教程推荐

结构沟通力 -〔李忠秋〕

结构会议力 -〔李忠秋〕

云原生架构与GitOps实战 -〔王炜〕

Vue 3 企业级项目实战课 -〔杨文坚〕

手把手带你写一门编程语言 -〔宫文学〕

分布式数据库30讲 -〔王磊〕

图解 Google V8 -〔李兵〕

安全攻防技能30讲 -〔何为舟〕

深入浅出计算机组成原理 -〔徐文浩〕

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