typestar

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

  1. function Monster:hit(damage) hides a self parameter.
  2. wight:hit(4) passes the receiver automatically.
  3. Monster.__index = Monster makes instances find methods.

Keywords and builtins used here

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.

Type this snippet

Step 3 of 3 in Metatables, step 19 of 27 in Language basics.

← Previous Next →