Lua语法(六)——面相对象编程

参考链接:
系列链接: Lua语法(一)
系列链接: Lua语法(二)------闭包/日期和时间
系列链接: Lua语法(三)------元表与元方法
系列链接: Lua语法(四)------协程
系列链接: Lua语法(五)------垃圾回收
系列链接: Lua语法(六)------面相对象编程
使用Lua表 进行类的模拟,从而面向对象编程

Lua语法 六------面相对象编程

面向对象编程

类创建

Lua中没有类这个类型,所以只有用表来模拟类

创建类方法的方式

方式1:表内用键值对的方式

方式2:表外使用 : 冒号

方式3:表外使用 点 .

案例见下方代码

冒号和点的区别

冒号是点的缩写形式,可以省略传入自身这个参数

综合案例:

lua 复制代码
--方式1  表内用键值对的方式
Show={
    score = 0,
    --使用键值对创建方法,如果要用到内部变量,需要加上self
    addScore = function (self,v)
        self.score = self.score + v
        print(self.score)
    end
}

--方式2  使用 : 冒号可以省略传入自己这个参数
function Show:decScore(v)
    self.score = self.score -v
    print(self.score)
end

--方式3   使用 点 . 需要添加上self
function Show.mulScore(self,v)
    self.score = self.score + v*2
    print(self.score)
end

function Show:new(o)
    o = o or {}
    self.__index = self
    setmetatable(o,self)
    return o
end

local a = Show:new()
a:addScore(10)
a:decScore(5)
a.mulScore(a,5)     --使用点来调用方法必须要传入自己
--输出
10
5
15
继承
lua 复制代码
Show={
    score = 0,
    --使用键值对创建方法,如果要用到内部变量,需要加上self
    addScore = function (self,v)
        self.score = self.score + v
        print(self.score)
    end
}

--使用 : 冒号可以省略传入自己这个参数
function Show:decScore(v)
    self.score = self.score -v
    print(self.score)
end

--使用 点 . 需要添加上self
function Show.mulScore(self,v)
    self.score = self.score + v*2
    print(self.score)
end

function Show:new(o)
    o = o or {}
    self.__index = self
    setmetatable(o,self)
    return o
end
-------------继承自Show---------------
BigShow = Show:new()    --继承自Show

local big = BigShow:new{min =0}

big:addScore(10)
big:decScore(5)
-- big:mulScore(5)
big.mulScore(big,5)
print(big.min)

--输出
10
5
15
0
属性私有性---对偶表示

使用对偶表示,实现属性相对私有性。

lua 复制代码
local score ={}
Show = {}

function Show:addScore(v)
    score[self] = score[self] + v
end

function Show:decScore(v)
    score[self] = score[self] - v
end

function Show:score(v)
    return score[self]
end

function Show:new(o)
    o = o or {}
    setmetatable(o,self)
    self.__index = self
    score[o]=0  --初始化分数
    return o
end

local big = Show:new()
big:addScore(10)    --只能通过方法进行修改内部属性值
print(big:score())  --只能通过方法访问内部属性
print(big.score(big))

--输出
10
10

参考链接:
系列链接: Lua语法(一)
系列链接: Lua语法(二)------闭包/日期和时间
系列链接: Lua语法(三)------元表与元方法
系列链接: Lua语法(四)------协程
系列链接: Lua语法(五)------垃圾回收
系列链接: Lua语法(六)------面相对象编程

相关推荐
weixin_3831964712 小时前
java基础面试题@Autowired和@Resource区别
java·开发语言
言乐613 小时前
Python游戏水平测试辅助系统2
开发语言·windows·python·游戏·django
我不是疯子是傻子13 小时前
Qt 实时曲线卡顿优化:从QPainter到OpenGL的3级加速实战
开发语言·qt
zlinear数据采集卡13 小时前
D223 ADC数据处理流水线:从原始采样值到工程单位的完整转换链
开发语言·arm开发·嵌入式硬件·fpga开发·开源·c#
nnerddboy14 小时前
Rust教程04:引用、借用与切片
开发语言·后端·rust
jerryinwuhan14 小时前
《Python数据预处理》第四章
开发语言·python
长江&后浪14 小时前
防火墙的描述
开发语言·网络·php
观无15 小时前
若依EasyExcel实现单元格合并
开发语言·前端·javascript
雨晨源码(同名B站)15 小时前
基于Python的网易云音乐评论数据情感化分析系统 音乐爬虫信息可视化 |SnowNLP评论情感分析
开发语言·hadoop·爬虫·python·信息可视化·毕业设计
我不是疯子是傻子15 小时前
串口通信数据帧粘包拆包再进化:基于 Qt 的滑动窗口与 CRC 校验实战
开发语言·qt