Menu
CoddyTech

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 table

When 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 works

Both 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 icon

Challenge

Easy

Create a table named player with a field score initialized to 0.

Add two functions to the table:

  1. player.setScore(self, value) - defined with dot syntax and explicit self parameter. Sets self.score to the given value.
  2. player:addBonus(amount) - defined with colon syntax. Adds amount to self.score.

You will receive two inputs:

  1. An initial score value
  2. A bonus amount to add

Perform the following steps:

  1. Call setScore using dot syntax (passing the table as the first argument) to set the initial score
  2. Call addBonus using colon syntax to add the bonus
  3. 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)
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Object Oriented Programming

Practice on your own: Online Lua compiler