typestar

Closures in Lua

A function captures the locals around it, alive between calls.

-- A closure captures the locals around it, alive between calls.
local function make_counter(label)
  local seen = 0
  return function()
    seen = seen + 1
    return label .. " #" .. seen
  end
end

local kills = make_counter("skeleton")
local finds = make_counter("relic")

print(kills())
print(kills())
print(finds())
print(kills())

How it works

  1. make_counter returns a function still holding seen.
  2. Each returned counter owns its own upvalue.
  3. Calls interleave without crosstalk between the two.

Keywords and builtins used here

The run, in numbers

Lines
16
Characters to type
322
Tokens
64
Three-star pace
70 tpm

At the three-star pace of 70 tokens a minute, this run takes about 55 seconds.

Type this snippet

Step 1 of 3 in Closures, step 14 of 27 in Language basics.

← Previous Next →

Closures in other languages