← Back to Lua Course | Chapter 6: OOP with Metatables | Lesson 5 of 7

Inheritance

A subclass can reuse a parent class by chaining metatables so missing methods are looked up upward.

In this page:

  1. Inheritance

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

lua
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
Common Mistakes
  1. Forgetting to set the child's own __index
  2. Overriding a method and forgetting to call the parent version when needed
  3. 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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.