Simple Mixins
Part of the Object Oriented Programming section of Coddy's Lua journey — lesson 51 of 70.
Composition lets you put objects inside other objects. But what if you want to share behavior across unrelated classes?
A Player and a MenuItem might both need a :describe() method, but they don't share a parent class. This is where mixins come in.
A mixin is simply a table containing functions. You "mix" these functions into a class by copying them over:
local Printable = {}
function Printable:describe()
print("Object: " .. tostring(self))
end
function Printable:log(message)
print("[LOG] " .. message)
endTo apply this mixin to a class, you copy each function from the mixin table into the class table:
local function applyMixin(class, mixin)
for key, value in pairs(mixin) do
class[key] = value
end
end
local Player = {}
Player.__index = Player
applyMixin(Player, Printable) -- Now Player has :describe() and :log()After applying the mixin, any Player instance can call those methods as if they were defined directly on the class:
local p = setmetatable({}, Player)
p:log("Player created") -- [LOG] Player createdUnlike inheritance, mixins don't create a parent-child relationship. You're simply copying functions from one table to another.
This makes mixins perfect for sharing utility behaviors—like logging, serialization, or description methods—across classes that otherwise have nothing in common.
Challenge
EasyLet's build a tagging system using mixins! You'll create a Taggable mixin that can be applied to any class, giving objects the ability to manage a collection of tags—useful for categorizing items, posts, or any entity that needs labels.
You'll organize your code across three files:
Taggable.lua: Create a mixin table containing two methods::addTag(tag)— adds a tag toself.tags(assumes the table exists):listTags()— prints all tags in the formatTags: tag1, tag2, tag3(orTags: noneif empty)
Article.lua: Create an Article class with a constructor:new(title)that stores the title and initializes an emptytagstable. Apply the Taggable mixin to give Article instances tagging capabilities. Include a:getTitle()method that returns the article's title.main.lua: Write theapplyMixinhelper function here (you'll use it in Article.lua via require). Then read inputs for an article title and two tags. Create an Article, add both tags to it, print the title, and list all tags.
You will receive three inputs:
- The article title (a string)
- The first tag to add (a string)
- The second tag to add (a string)
Your output should display the article's title followed by its tags:
Title: {title}
Tags: {tag1}, {tag2}For example, if the inputs are Lua Basics, programming, and tutorial, the output should be:
Title: Lua Basics
Tags: programming, tutorialRemember: the mixin methods work because Article instances have a tags table that the mixin methods can operate on. The mixin doesn't create this table—your Article constructor does. The mixin just provides the shared behavior!
Cheat sheet
A mixin is a table containing functions that can be shared across unrelated classes without creating a parent-child relationship.
To create a mixin, define a table with methods:
local Printable = {}
function Printable:describe()
print("Object: " .. tostring(self))
end
function Printable:log(message)
print("[LOG] " .. message)
endTo apply a mixin to a class, copy its functions into the class table:
local function applyMixin(class, mixin)
for key, value in pairs(mixin) do
class[key] = value
end
end
local Player = {}
Player.__index = Player
applyMixin(Player, Printable)After applying the mixin, instances can call the mixin methods:
local p = setmetatable({}, Player)
p:log("Player created") -- [LOG] Player createdMixins are ideal for sharing utility behaviors like logging, serialization, or tagging across classes that don't share inheritance.
Try it yourself
-- Main file for the tagging system
local Taggable = require('Taggable')
local Article = require('Article')
-- TODO: Implement the applyMixin function
-- This function should copy all methods from a mixin table to a target table
function applyMixin(target, mixin)
-- TODO: Loop through the mixin and copy each method to target
end
-- Read inputs
local title = io.read()
local tag1 = io.read()
local tag2 = io.read()
-- TODO: Create an Article with the given title
-- TODO: Add both tags to the article
-- TODO: Print the title in format: Title: {title}
-- TODO: List all tags using the listTags method
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Object Oriented Programming
1The 'Self' Concept
Tables with FunctionsExplicit 'self'The Colon SyntaxDot vs ColonRecap - Moving Point4Project: Digital Bank
Project SetupDeposit Method7Polymorphism & Overriding
Overriding MethodsCalling Parent MethodsDuck TypingCommon InterfaceChecking TypeRecap - Employee Roles10Project: Shape Manager
Project SetupRectangle Class2Class Prototype Pattern
The Prototype ConceptLinking with __indexThe :new() ConstructorInitializing AttributesIndependent InstancesRecap - Car Factory5Operator Overloading in OOP
Adding ObjectsSubtracting ObjectsConcatenating ObjectsComparing Objects (<, >)Recap - Wallet Math8Encapsulation
Naming ConventionsClosures for PrivacyAccess via ClosuresRead-Only TablesValidation LogicRecap - Secure Vault11Design Patterns (Lite)
Factory FunctionsSingleton TableIterator PatternObserver (Listener)Recap - Logger Factory3Object State and Behavior
Instance VariablesGetter MethodsSetter MethodsCalculated PropertiesFormatting StringsEquality ChecksRecap - Student Grade6Inheritance Basics
The Inheritance SetupInheriting MethodsExtending the ConstructorAdding Child MethodsShared vs UniqueRecap - Shape Hierarchy9Composition & Mixins
Has-A RelationshipDelegationSimple MixinsApplying Multiple MixinsMixins vs InheritanceRecap - Robot Assembly