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
make_counterreturns a function still holdingseen.- Each returned counter owns its own upvalue.
- Calls interleave without crosstalk between the two.
Keywords and builtins used here
endfindsfunctionkillslocalmake_counterprintreturn
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.
Step 1 of 3 in Closures, step 14 of 27 in Language basics.