TExcelTAD
Home › Lua › Lua Inheritance

Lua Inheritance

Inheritance lets a class reuse and extend another class. In Lua it falls out of the __index chain: a subclass is a table whose metatable points to the parent class, so a method missing from the object is looked up in the subclass, then in the parent, and so on.

lua · try it yourself
local Animal = {}
Animal.__index = Animal

function Animal.new(name, sound)
  return setmetatable({ name = name, sound = sound }, Animal)
end
function Animal:speak() return self.name .. " says " .. self.sound end
function Animal:describe() return "an animal called " .. self.name end

-- Dog inherits from Animal
local Dog = setmetatable({}, { __index = Animal })
Dog.__index = Dog

function Dog.new(name)
  local self = Animal.new(name, "woof")   -- reuse the parent constructor
  return setmetatable(self, Dog)          -- but make it a Dog
end
function Dog:fetch() return self.name .. " fetches the ball" end

local d = Dog.new("Rex")
print(d:speak())      -- inherited from Animal
print(d:fetch())      -- defined on Dog
print(d:describe())
Rex says woof
Rex fetches the ball
an animal called Rex

The lookup for d:speak goes: the object d (no speak) → its metatable Dog's __index, i.e. Dog (no speak) → Dog's metatable's __index, i.e. Animal (found).

Overriding and calling the parent

A subclass can override a method by defining one with the same name. To extend the parent's behaviour instead of replacing it, call the parent method explicitly with Parent.method(self, …):

lua · try it yourself
local Shape = {}
Shape.__index = Shape
function Shape.new(name) return setmetatable({ name = name }, Shape) end
function Shape:area() return 0 end
function Shape:describe()
  return string.format("%s with area %.2f", self.name, self:area())
end

local Circle = setmetatable({}, { __index = Shape })
Circle.__index = Circle
function Circle.new(r)
  local self = setmetatable(Shape.new("circle"), Circle)
  self.r = r
  return self
end
function Circle:area() return math.pi * self.r ^ 2 end              -- override
function Circle:describe()
  return Shape.describe(self) .. ", radius " .. self.r              -- extend
end

print(Shape.new("blob"):describe())
print(Circle.new(2):describe())
blob with area 0.00
circle with area 12.57, radius 2

Shape.describe calls self:area(), which finds Circle.area for a circle. That is polymorphism: the same code works with any subclass.

A reusable class helper

Writing the boilerplate for every class gets tedious. Many projects use a tiny helper like this one (libraries such as middleclass or classic work the same way):

lua · try it yourself
local function class(parent)
  local c = {}
  c.__index = c
  if parent then setmetatable(c, { __index = parent }) end
  c.new = function(...)
    local obj = setmetatable({}, c)
    if obj.init then obj:init(...) end
    return obj
  end
  c.super = parent
  return c
end

local Employee = class()
function Employee:init(name, salary) self.name, self.salary = name, salary end
function Employee:pay() return self.salary end
function Employee:summary() return self.name .. ": " .. self:pay() end

local Manager = class(Employee)
function Manager:init(name, salary, bonus)
  Manager.super.init(self, name, salary)
  self.bonus = bonus
end
function Manager:pay() return Manager.super.pay(self) + self.bonus end

local staff = { Employee.new("Ola", 3000), Manager.new("Kim", 4000, 1500) }
for _, e in ipairs(staff) do print(e:summary()) end
Ola: 3000
Kim: 5500

Checking an object's class

To test whether an object is an instance of a class (or of a subclass), walk up the metatable chain:

lua · try it yourself
local Base = {}; Base.__index = Base
local Mid = setmetatable({}, { __index = Base }); Mid.__index = Mid
local Other = {}; Other.__index = Other

local function isInstance(obj, cls)
  local mt = getmetatable(obj)
  while mt do
    if mt == cls then return true end
    local parent = getmetatable(mt)
    mt = parent and parent.__index
  end
  return false
end

local m = setmetatable({}, Mid)
print(isInstance(m, Mid), isInstance(m, Base), isInstance(m, Other))
true	true	false

Composition over inheritance

Deep inheritance chains get hard to follow. Game code in particular often prefers composition: an entity has components (a position, a health bar, a sprite) instead of being a subclass of a subclass. In Lua that is just a table holding other tables, and mixins (copying methods from one table into another) are a cheap way to share behaviour.

Test yourself

How does a Lua subclass inherit the parent's methods?

  1. With the extends keyword
  2. Its metatable's __index points to the parent class
  3. By copying _G
  4. With require

How do you call the parent's version of an overridden method area?

  1. super:area()
  2. Parent.area(self)
  3. self.super()
  4. base.area()

In the class helper, what does obj:init(...) do?

  1. Creates the metatable
  2. Runs the constructor logic with the arguments of new
  3. Copies the parent
  4. Nothing