Mixin Composition and Interface Checks
Mix in multiple behavior tables and validate interface conformance.
What Are Mixins?
Mixins are tables of methods copied into a class. They provide behavior without requiring an inheritance relationship — perfect for cross-cutting concerns.
Simple Mixin Application
Copy methods from a mixin table into the target class.
local Serializable = {
serialize = function(self)
local parts = {}
for k, v in pairs(self) do
parts[#parts+1] = k .. "=" .. tostring(v)
end
return "{" .. table.concat(parts, ", ") .. "}"
end
}
local function mixin(cls, ...)
for _, m in ipairs({...}) do
for k, v in pairs(m) do
if cls[k] == nil then cls[k] = v end
end
end
end
mixin(Animal, Serializable)
print(cat:serialize())All lessons in this course
- Base Class and Constructor Design
- Multi-Level Inheritance
- Mixin Composition and Interface Checks
- instanceof and Type Introspection