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
coroutine.createwraps a function into a resumable thread.yieldsends a value out and suspends mid-loop.statusreads suspended or dead as the walk progresses.
Keywords and builtins used here
doendforfunctioninipairslocalprintreturnselect
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.
Step 3 of 3 in Patterns & errors, step 22 of 27 in Language basics.