Deep inheritance hierarchies often lead to the "Fragile Base Class" problem in game development. Modern Lua architectures favor Composition over Inheritance using Mixins and Entity-Component Systems (ECS).
The Mixin Pattern
A Mixin is a table containing reusable methods that can be injected into any class prototype:
-- Mixin providing serialization capabilities
local Serializable = {
serialize = function(self)
local entries = {}
for k, v in pairs(self) do
entries[#entries + 1] = string.format("%s=%s", tostring(k), tostring(v))
end
return "{" .. table.concat(entries, ", ") .. "}"
end
}
-- Mixin providing event broadcasting
local EventDispatcher = {
on = function(self, event, callback)
self._listeners = self._listeners or {}
self._listeners[event] = self._listeners[event] or {}
table.insert(self._listeners[event], callback)
end,
trigger = function(self, event, ...)
if self._listeners and self._listeners[event] then
for _, cb in ipairs(self._listeners[event]) do
cb(...)
end
end
end
}
-- Function to compose mixins into a class
local function applyMixins(targetClass, ...)
for _, mixin in ipairs({...}) do
for k, v in pairs(mixin) do
targetClass[k] = v
end
end
end
-- Example Class
local Player = {}
Player.__index = Player
applyMixins(Player, Serializable, EventDispatcher)
local p1 = setmetatable({ name = "Valerie", level = 20 }, Player)
p1:on("levelup", function(newLevel)
print("Level up event triggered! New level: " .. newLevel)
end)
p1:trigger("levelup", 21)
print(p1:serialize())
Entity-Component Pattern (ECS in Games)
In game engines like Roblox or Love2D, game objects (Entities) are lightweight ID containers, and functionality is attached via discrete Components:
local function createEntity(id)
local entity = {
id = id,
components = {}
}
function entity:addComponent(name, data)
self.components[name] = data
return self
end
function entity:getComponent(name)
return self.components[name]
end
function entity:hasComponent(name)
return self.components[name] ~= nil
end
return entity
end
-- Create an entity composed dynamically:
local player = createEntity(1)
:addComponent("Transform", { x = 10, y = 20, rotation = 0 })
:addComponent("Health", { current = 100, max = 100 })
:addComponent("Physics", { velocityX = 5, velocityY = 0 })
Exercises
- Implement a complete ECS Movement System that iterates over all entities containing both
TransformandPhysicscomponents. - Build a
Damageablemixin that manages health, shield absorption, and a death event callback. - Compare the memory and maintainability trade-offs of classical inheritance versus component composition in a game with 50 unique mob types.