Initializing Attributes
Part of the Object Oriented Programming section of Coddy's Lua journey — lesson 9 of 70.
The :new() constructor you learned creates objects, but every instance starts identical. Real objects need unique data—a person has a specific name, a player has a starting score. To make objects useful, the constructor must accept arguments and assign them to the new instance.
Here's how to expand the constructor to accept initial values:
local Dog = {}
Dog.__index = Dog
function Dog:new(name, breed)
local instance = {}
setmetatable(instance, self)
instance.name = name
instance.breed = breed
return instance
end
function Dog:introduce()
print("I am " .. self.name .. ", a " .. self.breed)
endThe constructor now takes name and breed as parameters. After creating the empty instance and setting its metatable, we assign these values directly to the instance's fields. Each object created will have its own name and breed.
local dog1 = Dog:new("Rex", "German Shepherd")
local dog2 = Dog:new("Bella", "Poodle")
dog1:introduce() -- Output: I am Rex, a German Shepherd
dog2:introduce() -- Output: I am Bella, a PoodleBoth dogs share the same :introduce() method from the prototype, but each has its own unique name and breed stored in its instance table. This is the power of combining prototypes with parameterized constructors—shared behavior with individual state.
Challenge
EasyLet's build a Person class that creates unique individuals with their own names and ages. You'll organize your code across two files to practice proper module structure.
You'll create:
Person.lua: Define yourPersonclass with a constructor that accepts a name and age. Include a:introduce()method that lets each person introduce themselves.main.lua: Require your Person module and create a person instance using the provided inputs. Then have them introduce themselves.
Your :new(name, age) constructor should accept both values and store them on the new instance. The :introduce() method should print in this exact format:
Hello, my name is [name] and I am [age] years oldYou will receive two inputs:
- The person's name
- The person's age
For example, if the inputs are Alice and 25, the output should be:
Hello, my name is Alice and I am 25 years oldCheat sheet
To create objects with unique data, expand the :new() constructor to accept parameters and assign them to the instance:
local Dog = {}
Dog.__index = Dog
function Dog:new(name, breed)
local instance = {}
setmetatable(instance, self)
instance.name = name
instance.breed = breed
return instance
end
function Dog:introduce()
print("I am " .. self.name .. ", a " .. self.breed)
endCreate instances with different values:
local dog1 = Dog:new("Rex", "German Shepherd")
local dog2 = Dog:new("Bella", "Poodle")
dog1:introduce() -- Output: I am Rex, a German Shepherd
dog2:introduce() -- Output: I am Bella, a PoodleEach object has its own unique data stored in its instance table, while sharing methods from the prototype.
Try it yourself
-- Require the Person module
local Person = require('Person')
-- Read input
local name = io.read()
local age = io.read()
-- TODO: Create a new Person instance using Person:new(name, age)
-- TODO: Call the introduce() method on your person instance
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