Setter Methods
Part of the Object Oriented Programming section of Coddy's Lua journey — lesson 14 of 70.
Getter methods let you read internal data through a controlled access point. Setter methods (also called mutator methods) do the opposite—they provide a controlled way to modify internal state.
Instead of directly assigning car.speed = 50, you call car:setSpeed(50):
local Car = {}
Car.__index = Car
function Car:new()
local instance = {}
setmetatable(instance, self)
instance.speed = 0
return instance
end
function Car:setSpeed(newSpeed)
self.speed = newSpeed
end
function Car:getSpeed()
return self.speed
endAt first glance, this seems like extra work for the same result. But setters become powerful when you need to add rules later. Imagine you want to ensure speed never goes negative or exceeds a maximum:
function Car:setSpeed(newSpeed)
if newSpeed < 0 then
self.speed = 0
elseif newSpeed > 200 then
self.speed = 200
else
self.speed = newSpeed
end
endNow every speed change goes through your validation logic. Any code using :setSpeed() automatically benefits from these checks without modification. This is the real value of setters—they create a single point where you control how data changes, making your objects safer and easier to maintain.
Challenge
EasyLet's build a Thermostat class that uses setter methods to control temperature in a smart way. Instead of allowing any temperature value, your thermostat will enforce reasonable limits—keeping the temperature within a comfortable range.
You'll organize your code across two files:
Thermostat.lua: Define yourThermostatclass with the standard prototype pattern. Each thermostat should track its currenttemperature. Include:- A
:new()constructor that initializes the temperature to20(a comfortable default) - A
:getTemperature()getter that returns the current temperature - A
:setTemperature(newTemp)setter that updates the temperature, but keeps it within bounds: minimum10and maximum30
- A
main.lua: Require your Thermostat module and create a thermostat instance. Use the setter to attempt different temperature changes and observe how the limits are enforced.
Your :setTemperature() method should enforce these rules:
- If the new temperature is below
10, set it to10 - If the new temperature is above
30, set it to30 - Otherwise, set it to the requested value
You will receive two inputs:
- First temperature to set
- Second temperature to set
In your main file, create a thermostat, then:
- Print the initial temperature
- Set the temperature to the first input value and print the result
- Set the temperature to the second input value and print the result
Print each temperature on its own line (just the number).
For example, if the inputs are 25 and 50, the output should be:
20
25
30Notice how the second attempt to set 50 results in 30—the setter enforces the maximum limit automatically!
Cheat sheet
Setter methods provide a controlled way to modify internal state, allowing you to add validation rules and constraints.
Basic setter method syntax:
function Car:setSpeed(newSpeed)
self.speed = newSpeed
endSetters with validation enforce rules when data changes:
function Car:setSpeed(newSpeed)
if newSpeed < 0 then
self.speed = 0
elseif newSpeed > 200 then
self.speed = 200
else
self.speed = newSpeed
end
endCombining getters and setters creates controlled access to object properties:
local Car = {}
Car.__index = Car
function Car:new()
local instance = {}
setmetatable(instance, self)
instance.speed = 0
return instance
end
function Car:setSpeed(newSpeed)
if newSpeed < 0 then
self.speed = 0
elseif newSpeed > 200 then
self.speed = 200
else
self.speed = newSpeed
end
end
function Car:getSpeed()
return self.speed
endSetters create a single point of control for data modification, making objects safer and easier to maintain. Any code using the setter automatically benefits from validation logic without modification.
Try it yourself
-- Require the Thermostat module
local Thermostat = require('Thermostat')
-- Read input
local temp1 = tonumber(io.read())
local temp2 = tonumber(io.read())
-- TODO: Create a thermostat instance
-- TODO: Print the initial temperature
-- TODO: Set the temperature to temp1 and print the result
-- TODO: Set the temperature to temp2 and print the result
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