The colon in Lua
Method definition and call pass self in one habit.
-- The colon passes self: method definition and call in one habit.
local Monster = {}
Monster.__index = Monster
function Monster.new(name, hp)
return setmetatable({ name = name, hp = hp }, Monster)
end
function Monster:hit(damage)
self.hp = self.hp - damage
return self.hp > 0 and (self.name .. " snarls") or
(self.name .. " crumbles")
end
local wight = Monster.new("barrow wight", 9)
print(wight:hit(4))
print(wight:hit(6))
How it works
function Monster:hit(damage)hides a self parameter.wight:hit(4)passes the receiver automatically.Monster.__index = Monstermakes instances find methods.
Keywords and builtins used here
Monsterendfunctionhitlocalnewprintreturnsetmetatable
The run, in numbers
- Lines
- 17
- Characters to type
- 427
- Tokens
- 105
- Three-star pace
- 65 tpm
At the three-star pace of 65 tokens a minute, this run takes about 97 seconds.
Step 3 of 3 in Metatables, step 19 of 27 in Language basics.