码迷,mamicode.com
首页 > 其他好文 > 详细

Lua笔记——1.模块Module

时间:2018-02-27 14:00:12      阅读:143      评论:0      收藏:0      [点我收藏+]

标签:函数调用   ima   code   开始   AC   public   mod   路径问题   时间   

身为一名萌新程序员,现在才体会到掌握一两门脚本语言是多么的有用。这段时间深感技术不足,为了对Lua的语法不那么生疏,还是先复习一下,把理解的写下来吧。

Lua 模块——Lua 5.1 开始加入模块管理机制,以require("egModule") 或者 require "egModule",进行简单的调用提前准备好的模块 egModule.lua

PS:自定义模块的加载路径问题暂时保留

egModule模块的书写格式:

--file : egModule.lua
--[[
Lua Code
模块的文件名应该与模块名保持一致
eg: 定义一个名为egModule的模块,文件名为egModule.lua]]--

egModule = {} --1st.初始化egModule模块

egModule.value1 = "Hello" --2nd.定义模块内部的常量
egModule.value2 = "Lua"

function egModule.func1() --3rd.定义可以在外部调用的共有函数
io.write("This is a public function func1.\n")
end

function egModule.func2()
print("This is a public function func2.\n")
end

local function func3() --4th.定义模块内部的私有函数
print("This is a local function func3.\n")
end

local function func4()
io.write("This is a local function fun4.\n")
end

function egModule.func5() --5th.定义共有函数调用模块内部的私有函数
io.write("This is a public function func5.\n")
func3()
func4()
end

return egModule --模块的最后return此模块/table


egModule模块的调用:

直接调用

--file : luaTest.lua
require "egModule"

theValue1 = egModule.value1 --直接调用模块中的常量
theValue2 = egModule.value2

print(theValue1 .."".. theValue2)

egModule.func1() --直接调用模块中的公共方法
egModule.func2()

egModule.func5() --通过公共方法调用模块中的私有方法

别名调用

--file : luaCode.lua
unit = require "egModule" --为模块egModule定义别名unit

print(unit.value1)
print(unit.value2)

unit.func1()
unit.func2()

unit.func5()


技术分享图片

Lua笔记——1.模块Module

标签:函数调用   ima   code   开始   AC   public   mod   路径问题   时间   

原文地址:https://www.cnblogs.com/sylvan/p/8478346.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!