0Pricing
Lua Academy · Lesson

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 — lesson 1 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Lua Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

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
end

Defining 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 Meow

Constructor 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"
end

Class 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)  -- 1

Copy 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
end

Equality Metamethod

Define __eq for meaningful equality comparisons between instances.

Animal.__eq = function(a, b)
  return a.name == b.name
end

Why 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.

Frequently asked questions

Is the “Base Class and Constructor Design” lesson free?

Yes — the full text of “Base Class and Constructor Design” is free to read here on the web, and the Lua Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Lua Academy course, upgrade to CoddyKit PRO.

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; this is — lesson 1 of 4, so you can start here or from the beginning and move at your own pace.

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

  1. Base Class and Constructor Design
  2. Multi-Level Inheritance
  3. Mixin Composition and Interface Checks
  4. instanceof and Type Introspection
← Back to Lua Academy