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

Errors and coroutine helpers

Errors inside a coroutine are caught by resume, and helper functions tell you where you are.

Errors and coroutine helpers

If a coroutine raises an error, coroutine.resume returns false and the error message and the coroutine becomes dead. coroutine.running returns the current coroutine and a boolean that is true for the main thread. coroutine.isyieldable tells whether the current code can yield, and in Lua 5.3 a coroutine can yield across a pcall.

Note: The main program is itself a coroutine, but it cannot yield.

Example: Errors and coroutine helpers

lua
local co = coroutine.create(function()
  error("oops", 0)
end)
print(coroutine.resume(co))
print(coroutine.status(co))

print(select(2, coroutine.running()))
print(coroutine.isyieldable())
coroutine.wrap(function()
  print(coroutine.isyieldable(), select(2, coroutine.running()))
  local ok, v = pcall(function() return coroutine.yield("across pcall") end)
  print(ok, v)
end)()

-- Output:
-- false	oops
-- dead
-- true
-- false
-- true	false
Common Mistakes
  1. Expecting an error inside a coroutine to crash the whole program
  2. Resuming a coroutine after it errored
  3. Trying to yield from the main thread
Chapter Summary
  • resume catches errors
  • A coroutine that errors is dead
  • coroutine.running identifies the current one
  • isyieldable checks if yield is allowed
🔒

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.