typestar

Custom iterators in Lua

The generic for drives any function that returns next values.

-- The generic for drives any iterator function you write.
local function torch_burn(hours)
  local left = hours
  return function()
    if left > 0 then
      left = left - 1
      return hours - left, left
    end
  end
end

for hour, remaining in torch_burn(4) do
  print(string.format("Hour %d: %d hours of light left",
    hour, remaining))
end

How it works

  1. The factory returns a closure holding the remaining hours.
  2. Returning nil ends the loop — that is the whole protocol.
  3. Two returns per step feed two loop variables.

Keywords and builtins used here

The run, in numbers

Lines
15
Characters to type
317
Tokens
57
Three-star pace
65 tpm

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

Type this snippet

Step 3 of 3 in Closures, step 16 of 27 in Language basics.

← Previous Next →