typestar

Coroutines in Lua

Pause at yield, resume where it left off.

-- A coroutine pauses at yield and resumes where it left off.
local patrol = coroutine.create(function()
  for _, post in ipairs({ "gate", "hall", "crypt" }) do
    coroutine.yield("guard reaches the " .. post)
  end
  return "patrol complete"
end)

print(select(2, coroutine.resume(patrol)))
print(select(2, coroutine.resume(patrol)))
print("Status mid-walk: " .. coroutine.status(patrol))
print(select(2, coroutine.resume(patrol)))
print(select(2, coroutine.resume(patrol)))
print("Status after: " .. coroutine.status(patrol))

How it works

  1. coroutine.create wraps a function into a resumable thread.
  2. yield sends a value out and suspends mid-loop.
  3. status reads suspended or dead as the walk progresses.

Keywords and builtins used here

The run, in numbers

Lines
14
Characters to type
518
Tokens
104
Three-star pace
60 tpm

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

Type this snippet

Step 3 of 3 in Patterns & errors, step 22 of 27 in Language basics.

← Previous Next →