LUA / CHAPTER 13
Coroutine suspension and result channels
AdvancedTrace cooperative control transfer explicitly.
By the end of this chapter
- Distinguish yield from completion
- Check resume success before using results
- Track values sent into a suspended coroutine
The idea
A Lua coroutine is a cooperatively scheduled execution context. Resume starts or continues it until it yields, returns, or fails. Yield suspends the coroutine and sends values back to its resumer; a later resume supplies values that become the results of that suspended yield expression. This bidirectional flow should be part of the protocol, not inferred from timing.
Coroutine.resume returns a success flag before the yielded or returned values. Check it before interpreting the remaining results as normal data. A completed coroutine is dead and cannot be resumed as if it were merely paused. Coroutines do not automatically provide parallel execution or safe access to shared mutable tables, so explicit ownership and scheduling still matter.
local co=coroutine.create(function(x)
local y=coroutine.yield(x+1)
return y*2
end)
local ok,a=coroutine.resume(co,3)
assert(ok); print(a)
local ok2,b=coroutine.resume(co,5)
assert(ok2); print(b)
print(coroutine.status(co))4 10 dead
The first resume yields four; the second sends five into the suspended yield, allowing the coroutine to return ten and finish.
Try it yourself
Design a coroutine that accepts work items across resumes and reports a tagged result for each.
Use your own editor for this exercise. Runnable challenges on CodeQuest are available for JavaScript, Python, and SQL.
CHECK YOUR UNDERSTANDING