Dot vs Colon
Part of the Object Oriented Programming section of Coddy's Lua journey. Lesson 4 of 70.
Now that you know both the dot and colon syntax, here is how they relate, and what goes wrong when the table is not passed.
Both colons are shorthand. Defining function game:addPoints(points) is the same as defining function game.addPoints(self, points), and calling game:addPoints(10) is the same as calling game.addPoints(game, 10). A method works as long as the table arrives as its first argument.
Here's what happens when the table is not passed:
local game = { score = 0 }
function game:addPoints(points)
self.score = self.score + points
end
-- WRONG: calling with dot, but no table passed
game.addPoints(10) -- Error! self is now 10, not the tableWhen you call game.addPoints(10), Lua doesn't automatically pass game. The value 10 becomes self, and self.score fails because 10 is a number, not a table.
A function defined with a dot and an explicit self works with a colon call, because the colon passes the table as that first argument:
function game.reset(self)
self.score = 0
end
-- Calling with colon: game:reset() is the same as game.reset(game)
game:reset() -- self correctly receives game, so this worksBoth definitions create the same function, so the choice is a convention: use the colon to define and call functions that work on self, and the dot for functions that don't use self. Then every call shows whether the table is passed.
Challenge
EasyCreate a table named player with a field score initialized to 0.
Add two functions to the table:
player.setScore(self, value)- defined with dot syntax and explicitselfparameter. Setsself.scoreto the given value.player:addBonus(amount)- defined with colon syntax. Addsamounttoself.score.
You will receive two inputs:
- An initial score value
- A bonus amount to add
Perform the following steps:
- Call
setScoreusing dot syntax (passing the table as the first argument) to set the initial score - Call
addBonususing colon syntax to add the bonus - Print the final value of
player.score
Remember: match how you call each function to how it was defined.
Try it yourself
-- Read input
local initialScore = tonumber(io.read())
local bonusAmount = tonumber(io.read())
-- TODO: Write your code below
-- 1. Create a table named 'player' with a field 'score' initialized to 0
-- 2. Add player.setScore(self, value) using dot syntax with explicit self
-- 3. Add player:addBonus(amount) using colon syntax
-- 4. Call setScore using dot syntax (passing table as first argument)
-- 5. Call addBonus using colon syntax
-- Output the final score
print(player.score)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 ClassCircle ClassPerimeter MethodShape CollectionTotal AreaFilter Shapes2Class 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 HierarchyPractice on your own: Online Lua compiler