Base Class and Constructor Design
Design a Class() factory that sets up metatables and new() constructors.
Base Class and Constructor Design is a free Lua Academy lesson on CoddyKit. This is lesson 1 of 4. Any 3 lessons of this learning path are free to read in full — after that, CoddyKit PRO unlocks every lesson, plus hands-on practice with a built-in code editor and a 24/7 AI tutor. It is part of the Lua Academy learning path, and your progress syncs across the web and the CoddyKit app. The Lua Academy course includes 4 lessons in total.
Goal: A Reusable Class Factory
We want a Class() function that returns a new class object with proper constructor, method lookup, and OOP semantics.
Class Factory Skeleton
The factory creates a class table with a metatable for method dispatch.
local function Class()
local cls = {}
cls.__index = cls
cls.__name = "AnonymousClass"
function cls:new(...)
local instance = setmetatable({}, cls)
if instance.init then instance:init(...) end
return instance
end
return cls
endDefining a Class
Create a class, define init (the constructor), and add methods.
local Animal = Class()
Animal.__name = "Animal"
function Animal:init(name, sound)
self.name = name
self.sound = sound
end
function Animal:speak()
print(self.name .. " says " .. self.sound)
end
local cat = Animal:new("Cat", "Meow")
cat:speak() -- Cat says MeowConstructor Pattern
The constructor :new(...) creates an instance via setmetatable({}, cls), then calls :init(...) for initialization. This separates allocation from initialization.
Class Name for Debugging
Store cls.__name and define __tostring so instances print meaningfully.
function Animal:__tostring()
return "<" .. Animal.__name .. ": " .. self.name .. ">"
end
print(tostring(cat)) -- <Animal: Cat>Default Values in init
Provide default values in init using or.
function Vehicle:init(opts)
self.speed = opts.speed or 0
self.fuel = opts.fuel or 100
self.engine = opts.engine or "petrol"
endClass Methods vs Instance Methods
Methods defined with function cls.method() are class methods (no self). Methods defined with function cls:method() receive the instance as self.
Static Properties
Properties set directly on the class table are shared by all instances (unless shadowed by instance fields).
Animal.count = 0
function Animal:init(name, sound)
Animal.count = Animal.count + 1
self.name = name; self.sound = sound
end
print(Animal.count) -- 0
Animal:new("Dog","Woof")
print(Animal.count) -- 1Copy Constructor
A :clone() method creates a copy of an instance by shallow-copying its fields.
function Animal:clone()
local copy = setmetatable({}, getmetatable(self))
for k, v in pairs(self) do copy[k] = v end
return copy
endEquality Metamethod
Define __eq for meaningful equality comparisons between instances.
Animal.__eq = function(a, b)
return a.name == b.name
endWhy Not rawget?
Use self.field (not rawget) to allow metamethod-based field access in derived classes. Only use rawget when bypassing is explicitly needed.
Constructor Design Question
Why is init called separately from the new allocator?
Recap: Base Class and Constructor
A Class() factory creates a table as a class, sets __index = cls for method lookup, and provides :new() + :init(). This is the foundation for all Lua OOP patterns.
Learn Lua with an AI tutor — free
Write and run real code in your browser, get instant help from a 24/7 AI tutor, and pick up where you left off on the web or in the app.
- Courses
- 40
- Lessons
- 159
Frequently Asked Questions
Is the “Base Class and Constructor Design” lesson free?
Yes — any 3 lessons of the Lua Academy learning path, including “Base Class and Constructor Design”, are free to read in full here on the web. After that, CoddyKit PRO unlocks every lesson, plus interactive practice with a built-in code editor and a 24/7 AI tutor. The Lua Academy course includes 4 lessons in total.
What will I learn in “Base Class and Constructor Design”?
Design a Class() factory that sets up metatables and new() constructors. You practise Lua Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Lua Academy?
No prior experience is required. Lua Academy on CoddyKit is structured for beginners through advanced learners, so you can start here or from the beginning and move at your own pace. This is lesson 1 of 4.
How long does the “Base Class and Constructor Design” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Lua Academy lesson?
Yes. Every Lua Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- Base Class and Constructor Design
- Multi-Level Inheritance
- Mixin Composition and Interface Checks
- instanceof and Type Introspection