Lua Coroutine Status
A coroutine status is a word that tells where a coroutine is in its life. It changes as the coroutine starts, pauses, runs, and ends.
A new coroutine starts suspended and ends dead
Create a coroutine that returns a number. Resume it once and check its status before and after.
local co = coroutine.create(function()
return 42
end)
print(coroutine.status(co))
local ok, value = coroutine.resume(co)
print(ok, value)
print(coroutine.status(co))A yielded coroutine is suspended again
The body reports its own status while it runs. It then yields a word and waits.
local co = coroutine.create(function()
print(coroutine.status(coroutine.running()))
coroutine.yield("paused")
end)
print(coroutine.status(co))
local ok, value = coroutine.resume(co)
print(ok, value)
print(coroutine.status(co))A resuming coroutine is normal while the other runs
An outer coroutine resumes an inner coroutine. The inner body checks the outer status while it runs.
local outer
local inner = coroutine.create(function()
print(coroutine.status(outer))
end)
outer = coroutine.create(function()
coroutine.resume(inner)
end)
coroutine.resume(outer)
print(coroutine.status(inner))
print(coroutine.status(outer))Example
local co = coroutine.create(function()
coroutine.yield("first")
return "last"
end)
print(coroutine.status(co))
local ok1, value1 = coroutine.resume(co)
print(ok1, value1)
print(coroutine.status(co))
local ok2, value2 = coroutine.resume(co)
print(ok2, value2)
print(coroutine.status(co))
local ok3, err = coroutine.resume(co)
print(ok3, err)Key points
- Status: coroutine.status returns the current status of a coroutine.
- Suspended: a suspended coroutine waits to start or to resume after a yield.
- Running: a running coroutine is the coroutine now executing.
- Normal: a normal coroutine waits while a coroutine it resumed is running.
- Dead: a dead coroutine has finished or failed and cannot run again.
In this example, the coroutine starts suspended and yields the word first on the first resume. The second resume runs it to its return value last and leaves it dead. The third resume fails because a dead coroutine cannot run again.
Note
a yielded coroutine is suspended even though its work is not finished.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
A coroutine has yielded and waits for its next resume. What does coroutine.status return for it?