← Back to Lua Course | Chapter 7: Coroutines | Lesson 3 of 7

yield and passing values

yield pauses a coroutine and hands values out, and resume hands values back in.

In this page:

  1. yield and passing values

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

lua
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
Common Mistakes
  1. Calling yield outside any coroutine
  2. Confusing the arguments of the first resume with those of later ones
  3. 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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.