0Pricing
Lua Academy · Lesson

resume and yield

Exchange data between caller and coroutine with resume/yield.

Passing Values to Coroutine

Arguments passed to the first coroutine.resume become the function parameters of the coroutine body. Arguments passed to subsequent resumes are returned by the coroutine.yield() call that paused the coroutine.

local co = coroutine.create(function(a, b)
  print("received:", a, b)        -- 10  20
  local c = coroutine.yield()     -- pauses
  print("after yield:", c)        -- 30
end)

coroutine.resume(co, 10, 20)  -- first call: passes a,b
coroutine.resume(co, 30)      -- subsequent: passed to yield

Values from yield

Values passed to coroutine.yield(val1, val2) become the return values of the coroutine.resume() call that paused at the yield. So yield "returns" values to the caller.

local co = coroutine.create(function()
  coroutine.yield(1, "hello")
  coroutine.yield(2, "world")
  return 3, "done"
end)

local ok, a, b = coroutine.resume(co)
print(ok, a, b)   -- true  1  hello

ok, a, b = coroutine.resume(co)
print(ok, a, b)   -- true  2  world

ok, a, b = coroutine.resume(co)
print(ok, a, b)   -- true  3  done

All lessons in this course

  1. Creating Coroutines
  2. resume and yield
  3. Coroutine Status
  4. Producer-Consumer Pattern
← Back to Lua Academy