您的位置:首页 > 财经 > 产业 > Lua实现链表(面向对象应用)

Lua实现链表(面向对象应用)

2024/7/5 23:39:40 来源:https://blog.csdn.net/lzh824359508/article/details/140024519  浏览:    关键词:Lua实现链表(面向对象应用)

Lua实现面向对象

  • 面向对象核心三要素
  • Lua面向对象大致原理
    • 面向对象示例
    • 继承与多态示例

面向对象核心三要素

1.封装:对一个事物的抽象为一些属性和行为动作的集合,封装将属性和行为动作(操作数据的方法)绑定在一起,并隐藏对象的内部实现细节,只暴露给外部部分接口。
2. 继承是一种机制,允许一个类(子类)继承另一个类(父类)的属性和方法,从而实现代码重用和扩展。
3. 多态允许一个接口或方法在不同类的实例上有不同的表现形式。通过多态,可以编写更通用、更灵活的代码。

Lua面向对象大致原理

在 Lua 中,面向对象编程(OOP)的概念是通过表(table)和元表(metatable)来实现的。Lua 并没有内建的类系统,但通过灵活的元表机制,可以实现类、继承和多态等 OOP 特性。

面向对象示例

-- 下面通过实现一个简易的链表功能,来展示Lua实现面向对象的大致过程
local Node = {}
Node.__index = Node
Node.new = function(value)return setmetatable({value = value,next = nil},Node)
endlocal LinkList = {}
LinkList.__index = LinkList
LinkList.new = function()return setmetatable({head = nil},LinkList)
end
function LinkList:Insert(value)local node = Node.new(value)if not self.head thenself.head = nodeelselocal curNode = self.headwhile curNode.next docurNode = curNode.nextendcurNode.next = nodeend
endfunction LinkList:InsertByTable(valuetbl)for k,v in ipairs(valuetbl) dolocal node = Node.new(v)if not self.head thenself.head = nodeelselocal curNode = self.headwhile curNode.next docurNode = curNode.nextendcurNode.next = nodeendend
endfunction LinkList:Print()if not self.head thenprint("List has no node")elselocal curNode = self.headwhile curNode doprint("Cur Node Value:",curNode.value)curNode = curNode.nextendend
endfunction LinkList:Reverse()if not self.head thenprint("List has no node")elselocal preNode = nillocal curNode = self.headwhile curNode dolocal nextNode = curNode.nextcurNode.next = preNodepreNode = curNodecurNode = nextNodeendself.head = preNodeend
endlocal l = LinkList.new()
--l:Insert(2)
--l:Insert(4)
--l:Insert(5)
--l:Insert(1)
--l:Insert(0)
l:InsertByTable({1,2,3,4,"a"})
l:Print()
print("---------------------")
l:Reverse()
l:Print()

继承与多态示例

-- 定义一个基类
local Shape = {}
Shape.__index = Shapefunction Shape:new()local instance = setmetatable({}, self)return instance
endfunction Shape:area()return 0
end-- 定义一个子类,继承自 Shape
local Rectangle = setmetatable({}, Shape)
Rectangle.__index = Rectanglefunction Rectangle:new(width, height)local instance = Shape.new(self)instance.width = widthinstance.height = heightreturn instance
endfunction Rectangle:area()return self.width * self.height
end-- 定义另一个子类,继承自 Shape
local Circle = setmetatable({}, Shape)
Circle.__index = Circlefunction Circle:new(radius)local instance = Shape.new(self)instance.radius = radiusreturn instance
endfunction Circle:area()return math.pi * self.radius ^ 2
end-- 创建子类的实例,并展示多态行为
local shapes = {Rectangle:new(3, 4), Circle:new(5)}for _, shape in ipairs(shapes) doprint("Area:", shape:area())  -- 分别输出矩形和圆的面积
end

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com