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

Creating and resuming

coroutine.create makes a coroutine and coroutine.resume starts or continues it.

In this page:

  1. Creating and resuming

Creating and resuming

coroutine.create takes a function and returns a suspended coroutine without running it. coroutine.resume(co, ...) starts it, passing the arguments to the function, and returns true plus any results, or false plus an error message. coroutine.status reports suspended, running, normal or dead.

Note: Resuming a dead coroutine returns false and the message "cannot resume dead coroutine".

Example: Creating and resuming

lua
local co = coroutine.create(function(a, b)
  return a + b
end)
print(coroutine.status(co))
print(coroutine.resume(co, 3, 4))
print(coroutine.status(co))
print(coroutine.resume(co))

-- Output:
-- suspended
-- true	7
-- dead
-- false	cannot resume dead coroutine
Common Mistakes
  1. Forgetting to check the boolean that resume returns first
  2. Resuming a coroutine that is already dead
  3. Expecting create to run the function
Chapter Summary
  • create returns a suspended coroutine
  • resume returns true or false first
  • status shows the state
  • A finished coroutine is dead
🔒

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.