yield and passing values
yield pauses a coroutine and hands values out, and resume hands values back in.
In this page:
yield and passing values
Calling coroutine.yield(...) suspends the coroutine and makes the pending resume return true followed by the yielded values. The next resume call's extra arguments become the return values of that yield. This two-way exchange lets the caller and the coroutine talk to each other.
Note:
The first resume passes arguments to the function, later resumes pass values to yield.
Example: yield and passing values
local co = coroutine.create(function(a)
print("start", a)
local b = coroutine.yield(a * 2)
print("got", b)
local c = coroutine.yield(b + 1)
print("got", c)
return "finished"
end)
print(coroutine.resume(co, 10))
print(coroutine.resume(co, 20))
print(coroutine.resume(co, 30))
print(coroutine.status(co))
-- Output:
-- start 10
-- true 20
-- got 20
-- true 21
-- got 30
-- true finished
-- dead
Login to try C/C++/Java/PHP code in the editor
Common Mistakes
- Calling yield outside any coroutine
- Confusing the arguments of the first resume with those of later ones
- Forgetting that yield returns the next resume's arguments
Chapter Summary
- yield suspends and returns values to resume
- Later resume arguments come back from yield
- The first resume feeds the function parameters
- Yielding outside a coroutine is an error
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: