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