Getter Methods
Part of the Object Oriented Programming section of Coddy's Lua journey — lesson 13 of 70.
You've learned to store data in instance variables like self.health or self.items. While you can access these fields directly from outside the object, there's a cleaner approach: using getter methods.
A getter (also called an accessor method) is a simple method that returns an internal value. Instead of accessing player.health directly, you call player:getHealth():
local Player = {}
Player.__index = Player
function Player:new(name)
local instance = {}
setmetatable(instance, self)
instance.name = name
instance.health = 100
return instance
end
function Player:getHealth()
return self.health
end
function Player:getName()
return self.name
endWhy bother with an extra method? Getters provide a controlled access point to your data.
Right now, :getHealth() simply returns the value. But later, you might want to add logic—perhaps returning "Critical" if health drops below 10, or logging every time health is checked.
With a getter in place, you can make these changes without modifying any code that uses the object.
local hero = Player:new("Luna")
print(hero:getHealth()) -- Output: 100
print(hero:getName()) -- Output: LunaThis pattern creates a clear boundary between an object's internal structure and how other code interacts with it. The outside world asks for data through methods rather than reaching directly into the object's fields.
Challenge
EasyLet's build a Player class that uses getter methods to access its internal data. Instead of reaching directly into the player's fields, you'll create methods that provide controlled access to the player's information.
You'll organize your code across two files:
Player.lua: Define yourPlayerclass with the standard prototype pattern. The constructor should accept a name and initialize health to100. Add three getter methods::getName()returns the player's name:getHealth()returns the player's current health:getStatus()returns a formatted string combining both pieces of information
main.lua: Require your Player module and create a player instance. Use the getter methods to display the player's information—access everything through methods rather than directly reading fields.
Your :getStatus() method should return a string in this exact format:
[name] has [health] HPYou will receive one input: the player's name.
In your main file, create a player with the given name, then print three lines using your getter methods:
- The player's name (using
:getName()) - The player's health (using
:getHealth()) - The player's full status (using
:getStatus())
For example, if the input is Luna, the output should be:
Luna
100
Luna has 100 HPCheat sheet
A getter method (or accessor method) is a method that returns an internal value from an object. Instead of accessing fields directly, you call a method to retrieve the data.
Basic getter methods:
function Player:getHealth()
return self.health
end
function Player:getName()
return self.name
endUsing getter methods:
local hero = Player:new("Luna")
print(hero:getHealth()) -- Output: 100
print(hero:getName()) -- Output: LunaGetters provide a controlled access point to your data. They create a clear boundary between an object's internal structure and how other code interacts with it. This allows you to add logic later (such as validation or logging) without modifying code that uses the object.
Try it yourself
-- Require the Player module
local Player = require('Player')
-- Read input
local name = io.read()
-- TODO: Create a player instance with the given name
-- TODO: Print the player's name using :getName()
-- TODO: Print the player's health using :getHealth()
-- TODO: Print the player's status using :getStatus()
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