Inheritance
A subclass can reuse a parent class by chaining metatables so missing methods are looked up upward.
In this page:
Inheritance
To inherit, make the subclass's metatable point to the parent through __index, using setmetatable(Child, {__index = Parent}). A missing key is then searched in the instance, the child class, and finally the parent. The subclass can override methods and call the parent's version explicitly with Parent.method(self).
Note:
Call Parent.new(...) in the child constructor, then change the metatable to the child class.
Example: Inheritance
local Animal = {}
Animal.__index = Animal
function Animal.new(name) return setmetatable({name = name}, Animal) end
function Animal:speak() return self.name .. " makes a sound" end
local Cat = setmetatable({}, {__index = Animal})
Cat.__index = Cat
function Cat.new(name)
local self = Animal.new(name)
return setmetatable(self, Cat)
end
function Cat:speak() return Animal.speak(self) .. ": meow" end
local c = Cat.new("Tom")
print(c:speak())
print(Animal.new("Generic"):speak())
-- Output:
-- Tom makes a sound: meow
-- Generic makes a sound
Login to try C/C++/Java/PHP code in the editor
Common Mistakes
- Forgetting to set the child's own __index
- Overriding a method and forgetting to call the parent version when needed
- Creating a cycle of metatables
Chapter Summary
- Chain classes with __index
- Children override parent methods
- Call Parent.method(self) to extend
- Lookup goes instance, child, parent
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: