我正在努力理解元表是如何工作的,以及为什么在 Lua 中需要它们来创建类和继承。我为 Lua 找到的每个 OOP 示例都与上一个有所不同,但它们总是使用元表,特别是针对__index
属性。以下是我如何实现一些简单的继承:
Animal = {}
function Animal.New()
local self = {}
self.sName = "Generic Animal"
self.GetName = function(self)
return self.sName
end
self.Speak = function(self)
-- Do nothing, abstract function
end
return self
end
Dog = {}
function Dog.New()
local self = Animal.New()
self.sName = "Dog"
self.Speak = function(self)
print("Bark!")
end
return self
end
Labrador = {}
function Labrador.New()
local self = Dog.New()
self.sName = "Labrador"
return self
end
Chihuahua = {}
function Chihuahua.New()
local self = Dog.New()
self.sName = "Chihuahua"
self.Speak = function(self)
print("Yap yap!")
end
return self
end
-- Test --
l = Labrador.New()
print(l:GetName())
l:Speak()
c = Chihuahua.New()
print(c:GetName())
c:Speak()
d = Dog.New()
print(d:GetName())
d:Speak()
a = Animal.New()
print(a:GetName())
a:Speak()
输出:
Labrador
Bark!
Chihuahua
Yap yap!
Dog
Bark!
Generic Animal
据我所知,这很好用。使用元表将如何改进我的设计?