一般编程我们都知道一个习惯,就是不要讲所有的代码都放到一个脚本里面,
lua提供了一个模块化的方式,可以引入其他脚本的内容
使用require
注意,当使用require的时候,相当于在require这个位置,把对应的脚本全部运行一遍(不包括声明的内容)
看代码吧。
--模块 print("模块测试-----------------------------------------------------") -- local file_path = "D:\\studyDir\\gameDir\\lua\\code\\" -- require(file_path.."math_func") local math_func = require("math_func") -- 加载模块的时候,会调用到模块里面的代码,会有一行"math_func is load" local tmp = math_func.absa(-4)--通过导出模块进行调用 print(tmp) tmp = math_absa(-5)--通过直接调用方法 print(tmp) -- math_local_func() -- 模块内部方法,调用失败 require("device") --一次引入,全部地方都能使用 device.module_device_func() math_func.add(1,2)--在add方法里面,也调用了上面那行
这里需要用到,math_func.lua,device.lua,在同级目录下面新增这2个文件
math_func
local function math_local_func() print("math_local_func") end function math_absa(value) if (value<0) then return -value end return value end function math_add(value1,value2) device.module_device_func() return value1 + value2 end print("math_func is load") local list = { absa = math_absa, add = math_add, } return listdevice
module("device",package.seeall) function module_device_func() print("module_device_func") end
运行结果
math_func is load 4 5 module_device_func module_device_func
扫描二维码关注公众号,回复:
1730171 查看本文章
Lua学习之一环境搭建:https://blog.csdn.net/cmqwan/article/details/80742135
Lua学习之二基本类型:https://blog.csdn.net/cmqwan/article/details/80742990
Lua学习之三流程控制:https://blog.csdn.net/cmqwan/article/details/80749169
Lua学习之四循环 :https://blog.csdn.net/cmqwan/article/details/80749241
Lua学习之五面向对象:https://blog.csdn.net/cmqwan/article/details/80749348
Lua学习之六模块 :https://blog.csdn.net/cmqwan/article/details/80752806
Lua学习之七源码 :https://blog.csdn.net/cmqwan/article/details/80752873