The :new() Constructor
Part of the Object Oriented Programming section of Coddy's Lua journey — lesson 8 of 70.
Creating objects manually—making an empty table, setting its metatable, linking __index—gets repetitive. The standard solution is to define a :new() constructor method directly in the class that handles all of this for you.
Here's the pattern:
local Dog = {}
Dog.__index = Dog
function Dog:new()
local instance = {}
setmetatable(instance, self)
return instance
end
function Dog:bark()
print("Woof!")
endLet's break down what happens inside :new(). First, we create an empty table called instance. Then we set its metatable to self—which is Dog when we call Dog:new().
Since Dog.__index points to Dog itself, the instance can find all methods defined in Dog. Finally, we return the new object.
Notice the line Dog.__index = Dog outside the constructor. This is a common shortcut—instead of creating a separate metatable, the class table serves as both the prototype and the metatable.
Now creating objects is clean and consistent:
local myDog = Dog:new()
myDog:bark() -- Output: Woof!Every class you create will follow this same structure. The :new() constructor becomes the single place where object creation happens, making your code organized and predictable.
Challenge
EasyLet's build a Cat class using the standard constructor pattern you just learned. You'll organize your code across two files to practice proper module structure.
You'll create:
Cat.lua: Define yourCatclass with the complete constructor pattern. Your class should include:- The class table with
__indexpointing to itself - A
:new()constructor that creates an instance, sets its metatable, and returns it - A
:meow()method that prints the cat's sound
- The class table with
main.lua: Require your Cat module and use the constructor to create a cat instance. Then call its method to verify everything is linked correctly.
You will receive one input: the number of times your cat should meow.
Your :meow() method should print exactly:
Meow!In your main file, create a cat using Cat:new() and call :meow() the specified number of times.
For example, if the input is 3, the output should be:
Meow!
Meow!
Meow!Cheat sheet
To create a class with a constructor in Lua, define a :new() method that creates instances:
local ClassName = {}
ClassName.__index = ClassName
function ClassName:new()
local instance = {}
setmetatable(instance, self)
return instance
end
function ClassName:method()
-- method implementation
endThe __index field points to the class itself, allowing instances to access methods defined in the class table.
Inside :new():
- Create an empty table for the instance
- Set its metatable to
self(the class) - Return the new instance
Create objects using the constructor:
local obj = ClassName:new()
obj:method()Try it yourself
-- Require the Cat module
local Cat = require('Cat')
-- Read input: number of times to meow
local times = tonumber(io.read())
-- TODO: Create a cat instance using Cat:new()
-- TODO: Call the :meow() method the specified number of times
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 Hierarchy