Lua Coroutine Errors
A coroutine error is a failure inside a coroutine body that stops that coroutine. Resume reports the failure instead of letting it stop the whole program.
Resume reports a body error as false and a message
The body fails with the word boom. The check shows the message ends with that word and the status is dead.
local co = coroutine.create(function()
error("boom")
end)
local ok, err = coroutine.resume(co)
print(ok)
print(err:sub(-4) == "boom")
print(coroutine.status(co))A failed coroutine cannot be resumed again
The first resume fails the body. The second resume reports that the coroutine is dead.
local co = coroutine.create(function()
error("boom")
end)
coroutine.resume(co)
local ok, err = coroutine.resume(co)
print(ok, err)An error in a stage stops the pipeline cleanly
The source yields 7 and then fails. The filter stops and the main program still prints the source status.
local source = coroutine.create(function()
coroutine.yield(7)
error("boom")
end)
local filter = coroutine.create(function()
while true do
local ok, value = coroutine.resume(source)
if not ok then
break
end
if value == nil then
break
end
coroutine.yield(value)
end
end)
while coroutine.status(filter) ~= "dead" do
local ok, value = coroutine.resume(filter)
if value then
print(value)
end
end
print(coroutine.status(source))Example
local bad = coroutine.create(function()
coroutine.yield(1)
coroutine.yield(2)
error("boom")
end)
local good = coroutine.create(function()
coroutine.yield(10)
coroutine.yield(20)
end)
local ok, value = coroutine.resume(bad)
print(ok, value)
local ok2, value2 = coroutine.resume(bad)
print(ok2, value2)
local ok3, err = coroutine.resume(bad)
print(ok3, err:sub(-4) == "boom")
print(coroutine.status(bad))
local ok4, value4 = coroutine.resume(good)
print(ok4, value4)
local ok5, value5 = coroutine.resume(good)
print(ok5, value5)Key points
- Resume: resume returns false plus the error message when the body fails.
- Dead: a coroutine that failed is dead and cannot be resumed.
- Wrap: wrap raises a body error instead of returning false and a message.
- Check: the caller checks the first resume result before it uses any later value.
- Stage: an error in one pipeline stage stops that stage and the stages that pull from it.
In this example, the first coroutine yields 1 and 2 and then fails. The check shows its error message and its status is dead. The second coroutine still runs and yields 10 and 20.
Note
a failure inside a coroutine does not stop the main program when resume reports it.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
A coroutine body fails. What does a later resume return?