Errors and coroutine helpers
Errors inside a coroutine are caught by resume, and helper functions tell you where you are.
In this page:
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
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
Login to try C/C++/Java/PHP code in the editor
Common Mistakes
- Expecting an error inside a coroutine to crash the whole program
- Resuming a coroutine after it errored
- 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: