Tables with Methods and self
A table can hold data, and functions are values, so a table can hold functions too. A table that keeps both its data and the functions that work on that data is called an object. A function stored in an object is called a method.
local player = {name = "Alice", score = 0}
function player.addPoints(p, points)
p.score = p.score + points
end
player.addPoints(player, 10)
print(player.score)
Output:
10
function player.addPoints(p, points) stores a function in the addPoints field of player. The function gets the player as its first parameter, p. This works, but the call is long: you have to write player twice.
The colon and self
Lua has a shorter way. It is the same colon you used for string calls like s:upper().
local player = {name = "Alice", score = 0}
function player:addPoints(points)
self.score = self.score + points
end
function player:show()
print(self.name .. " has " .. self.score)
end
player:addPoints(10)
player:addPoints(5)
player:show()
Output:
Alice has 15
The colon works in two places:
- In a call,
player:addPoints(10)meansplayer.addPoints(player, 10). Lua passes the table before the colon as the first argument. - In a definition,
function player:addPoints(points)adds that first parameter for you. Its name is alwaysself.
So inside a method, self is the table the method was called on. Here it is player.
Tables are references, so self.score = self.score + points changes the real player table. The method does not need to return anything. After two calls, the score is 15.
Lua has no class keyword. For one object, a table with methods like this is all you need. To make many objects that share the same methods, Lua uses metatables. That is the next lesson.
In the exercise, complete the deposit method of a bank account so it adds money to self.balance.