I'm struggling to understand how metatables work and why they are needed in Lua for creating classes and for inheritance. Every OOP example I find for Lua is a little different from the last, but they always use metatables, specifically for the __index
property. Here is how I implemented some simple inheritance:
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()
Output:
Labrador
Bark!
Chihuahua
Yap yap!
Dog
Bark!
Generic Animal
So as far as I can see, this works just fine. How would using metatables improve my design?