Lua 無原生類機制,通過表存儲狀態/行為,配合元表實現繼承查找,構建靈活的面向對象體系。
-- 元類/基類
Rectangle = {area = 0, length = 0, breadth = 0}
-- 構造函數
function Rectangle:new(o, length, breadth)
o = o or {}
setmetatable(o, self)
self.__index = self -- 關鍵:啟用繼承查找
self.length = length or 0
self.breadth = breadth or 0
self.area = length * breadth
return o
end
-- 方法
function Rectangle:printArea()
print("The area of Rectangle is ", self.area)
end
-- 創建實例
local r = Rectangle:new(nil, 10, 20)
print(r.length) -- 訪問屬性
r:printArea() -- 調用方法 (冒號語法自動傳遞 self)
子類調用父類 :new() 獲取基礎表,再設置自己的元表,形成原型鏈:
Shape = {area = 0}
function Shape:new(o, side)
o = o or {}
setmetatable(o, self)
self.__index = self
side = side or 0
self.area = side * side
return o
end
function Shape:printArea()
print("The area is ", self.area)
end
-- Square 繼承 Shape
Square = Shape:new()
function Square:new(o, side)
o = o or Shape:new(o, side) -- 調用父類構造
setmetatable(o, self)
self.__index = self
return o
end
function Square:printArea() -- 重寫方法
print("The area of square is ", self.area)
end
-- Rectangle 繼承 Shape
Rectangle = Shape:new()
function Rectangle:new(o, length, breadth)
o = o or Shape:new(o)
setmetatable(o, self)
self.__index = self
self.area = length * breadth
return o
end
function Rectangle:printArea()
print("The area of Rectangle is ", self.area)
end
-- 測試
local myshape = Shape:new(nil, 10)
myshape:printArea() -- The area is 100
local mysquare = Square:new(nil, 10)
mysquare:printArea() -- The area of square is 100
local myrect = Rectangle:new(nil, 10, 20)
myrect:printArea() -- The area of Rectangle is 200
setmetatable(o, self):將實例的元表指向類表。self.__index = self:讓實例在自身找不到字段時,到類表查找(方法、默認屬性)。obj:method() 等價於 obj.method(obj),自動傳遞 self。可通過組合多個元表實現混入;利用 __call 元方法讓類表可直接調用構造(如 Rectangle(10,20))。
Lua 的 OOP 本質是基於原型的委託模式。掌握 setmetatable、__index、冒號調用三大支柱,即可構建清晰、可擴展的面向對象架構。