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

相关推荐
Cloud_Shy6188 分钟前
解读《Effective Python 3rd Edition》:从练气到老魔(第六章 Item 40 - 43)
android·开发语言·人工智能·笔记·python·学习方法
半只小闲鱼14 分钟前
配置计划模块通用办公设备家具批复数合计计算
开发语言·python
qq_4221525736 分钟前
Word 文件太大怎么压缩?2026 年文档瘦身方案对比
开发语言·c#·word
charliedev41 分钟前
Jedi:Python 自动补全与静态分析的实用工具
开发语言·python·其他
ji198594431 小时前
MATLAB 求散点曲线斜率
开发语言·算法·matlab
kaikaile19951 小时前
MATLAB 实现:Koch & Zhao 图像水印算法(DCT域)
开发语言·算法·matlab
love_muming1 小时前
链表每日一练
java·开发语言·数据结构·链表·idea·每日一练
weixin_446260851 小时前
LLM智能体在社交模拟中的决策行为分析:有限状态与LLM-based策略对比研究
开发语言·php
牛肉在哪里1 小时前
ros2 从零开始28 监听广播C++
开发语言·c++·算法·机器人
techdashen1 小时前
Cargo 1.94 开发周期全解析
开发语言·后端·rust