Skip to content
Tutorials Center
My learning

Topics

Lesson 18 of 32 ยท Metatables and OOP

Inheritance and Mixins

Learn inheritance in Lua with metatable chains: subclasses, calling a parent method, polymorphism, mixins that copy functions, and composition over inheritance.

In Objects and Classes an object looked up missing keys in its class. Inheritance is the same idea one level further: a class that looks up missing keys in a parent class. Lua does not need any special feature for it, only a longer chain of __index lookups.

This lesson shows the subclass pattern, how to call a parent's method, how polymorphism falls out of the lookup, and two alternatives to deep hierarchies: mixins and composition. Lua code is read-only; the runnable editors are JavaScript stand-ins using prototype chains.

The lookup chain

Object Its own fields first.
Subclass Then the subclass methods.
Parent class Then the parent's methods.
nil Nothing found anywhere.

The first table that has the key wins.

1 / 2

Subclassing with a metatable chain

To make Dog inherit from Animal, give Dog the metatable {__index = Animal}. Objects of Dog still have Dog as their metatable, so the full chain is: object, then Dog, then Animal.

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
function Animal:describe()
  return "I am " .. self.name
end

local Dog = setmetatable({}, {__index = Animal})   -- Dog falls back to Animal
Dog.__index = Dog

function Dog.new(name, breed)
  local self = Animal.new(name)       -- build the parent part
  self.breed = breed
  return setmetatable(self, Dog)      -- then switch to the subclass
end
function Dog:speak()                  -- overrides Animal:speak
  return self.name .. " barks"
end

local d = Dog.new("Rex", "collie")
print(d:speak())                      --> Rex barks
print(d:describe())                   --> I am Rex   (inherited)

d:describe() is not on d and not on Dog, so the lookup continues to Animal, where it is found. The subclass overrides speak simply by defining its own.

JS Stand-in: a subclass found through the chain

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Calling the parent's method

A subclass often wants to extend a parent method, not replace it. Lua has no super keyword, so you name the parent explicitly and pass self by hand:

LUA
function Dog:describe()
  local base = Animal.describe(self)        -- call the parent version
  return base .. ", a " .. self.breed
end
print(d:describe())                         --> I am Rex, a collie

Animal.describe(self) uses a dot and passes self explicitly; writing Animal:describe() would pass the class itself as self, which is a classic mistake. The same technique works in constructors, as in Dog.new above where the parent's new builds the base table.

Some code stores the parent in a field (Dog.super = Animal) so the name appears in only one place. That is a convention, not something Lua provides.

Polymorphism

Because the method is looked up at call time on the actual object, code that calls animal:speak() works for any class that provides speak. It does not need to know the class:

LUA
local pets = {Animal.new("Generic"), Dog.new("Rex", "collie")}
for _, pet in ipairs(pets) do
  print(pet:speak())
end
--> Generic makes a sound
--> Rex barks

Lua is dynamically typed, so even unrelated classes work as long as they have the methods you call. This is often called duck typing: if it has a speak method, treat it as something that can speak.

JS Stand-in: polymorphism and a super call

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Mixins

Not everything is an is-a relationship. A mixin is a table of functions that you copy into a class to add behavior without adding a parent. It is plain copying, no metatables involved:

LUA
local Serializable = {}
function Serializable:serialize()
  local parts = {}
  for k, v in pairs(self) do
    parts[#parts + 1] = k .. "=" .. tostring(v)
  end
  table.sort(parts)
  return "{" .. table.concat(parts, ", ") .. "}"
end

local function include(class, mixin)
  for name, fn in pairs(mixin) do
    class[name] = fn
  end
end

include(Dog, Serializable)
print(d:serialize())            --> {breed=collie, name=Rex}

The class receives its own references to the functions, so changes to the mixin made later do not appear in classes that already included it. The table.sort call keeps the output order stable, since pairs order is not guaranteed (see Iterating with pairs and ipairs).

JS Stand-in: copying a mixin into a class

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Composition over inheritance

Deep class hierarchies get brittle: a change in the root can break leaves several levels away. A sturdier habit is composition: build an object from smaller objects it holds, and forward calls to them. A Car has an Engine rather than being one:

LUA
local Engine = {}
Engine.__index = Engine
function Engine.new(power) return setmetatable({power = power}, Engine) end
function Engine:start() return "engine running at " .. self.power .. " hp" end

local Car = {}
Car.__index = Car
function Car.new(power)
  return setmetatable({engine = Engine.new(power)}, Car)
end
function Car:start() return self.engine:start() end

Keep inheritance to one or two levels for true is-a relationships, use mixins for small shared utilities, and compose for everything else.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. How do you make Dog inherit from Animal in the plain-metatable style?

    Failed lookups on Dog then continue in Animal. Lua has no extends keyword.
  2. 2. Inside Dog:describe, how do you call Animal's version?

    There is no super keyword. Name the parent class and pass self explicitly with a dot. Animal:describe() would pass Animal as self.
  3. 3. What is true about a mixin in the copying style shown here?

    include copies the function references into the class. Later changes to the mixin table do not affect classes that already copied from it.
  4. 4. Why does code like pet:speak() work for unrelated classes?

    Lua is dynamically typed. The call only needs the object to have a speak method.

Summary

  • Inheritance is a longer __index chain: object, subclass, parent class.
  • A subclass overrides a method by defining its own; call the parent with Parent.method(self, ...).
  • Polymorphism and duck typing come from looking methods up at call time.
  • Mixins copy functions into a class; sort or fix order where pairs order would leak into output.
  • Prefer composition (has-a) and shallow hierarchies for maintainable code.

Next, learn how to handle failures cleanly in Error Handling.