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

相关推荐
【赫兹威客】浩哥几秒前
【赫兹威客】Redis安装与验证教程
开发语言·php
froginwe11几秒前
SVG 简介
开发语言
宵时待雨2 分钟前
数据结构(初阶)笔记归纳7:链表OJ
c语言·开发语言·数据结构·笔记·算法·链表
无心水6 分钟前
8、吃透Go语言container包:链表(List)与环(Ring)的核心原理+避坑指南
java·开发语言·链表·微服务·架构·golang·list
froginwe1113 分钟前
Python3 集合
开发语言
lly20240617 分钟前
R 绘图 - 条形图
开发语言
无心水22 分钟前
6、Go语言类型判断与转换避坑指南:从类型断言到别名类型全解析
开发语言·后端·golang
a程序小傲25 分钟前
SpringBoot 秒实现在线 Word 编辑、协同、转化等功能
java·开发语言·spring boot·后端·spring·word·深度优先
Remember_99327 分钟前
【LeetCode精选算法】前缀和专题一
java·开发语言·数据结构·算法·leetcode·eclipse
孞㐑¥27 分钟前
算法—双指针
开发语言·c++·经验分享·笔记·算法