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

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

使用Lua表 进行类的模拟,从而面向对象编程

面向对象编程

类创建

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

创建类方法的方式

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

方式2:表外使用 : 冒号

方式3:表外使用 点 .

案例见下方代码

冒号和点的区别

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

综合案例:

--方式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
继承
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

属性私有性—对偶表示

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

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语法(六)——面相对象编程

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值