0Pricing
Lua Academy · Lesson

Mixin Patterns

Compose behavior by copying methods from multiple source tables.

What is a Mixin?

A mixin is a table of methods that can be copied into multiple classes. Unlike inheritance, mixins add behavior without establishing a parent-child relationship. A class can combine behaviors from multiple mixins.

local Flyable={}
function Flyable:fly()
  print(self.name.." is flying!")
end
function Flyable:land()
  print(self.name.." landed.")
end

local Bird={} Bird.__index=Bird
-- Mix in Flyable
for k,v in pairs(Flyable) do Bird[k]=v end

function Bird.new(name)
  return setmetatable({name=name},Bird)
end
Bird.new("Eagle"):fly()

Multiple Mixins

Apply multiple mixins to one class to compose complex behavior from simple pieces. This is horizontal composition — each mixin is independent.

local Serializable={}
function Serializable:toCSV(fields)
  local row={}
  for _,f in ipairs(fields) do row[#row+1]=tostring(self[f]) end
  return table.concat(row,",")
end

local Loggable={}
function Loggable:log(msg)
  print("["..os.date("%H:%M").."]["..self.name.."] "..msg)
end

local Entity={} Entity.__index=Entity
for k,v in pairs(Serializable) do Entity[k]=v end
for k,v in pairs(Loggable) do Entity[k]=v end

function Entity.new(n,v) return setmetatable({name=n,value=v},Entity) end
local e=Entity.new("item",42)
e:log("created"); print(e:toCSV({"name","value"}))

All lessons in this course

  1. Single Inheritance with __index Chaining
  2. Calling Parent Methods with super
  3. Mixin Patterns
  4. Overriding and Polymorphism
← Back to Lua Academy