Creating Coroutines
Create coroutines with coroutine.create and coroutine.wrap.
What is a Coroutine?
A coroutine is a function that can pause its execution (yield) and later resume from where it left off. Unlike threads, coroutines are cooperative — only one runs at a time, and they explicitly yield control. Lua coroutines have their own stack and local variables.
local co = coroutine.create(function()
print("start")
coroutine.yield()
print("resumed")
coroutine.yield()
print("done")
end)
print(coroutine.status(co)) -- suspended
coroutine.resume(co) -- start
print(coroutine.status(co)) -- suspended
coroutine.resume(co) -- resumedcoroutine.create vs coroutine.wrap
coroutine.create(fn) creates a coroutine and returns a coroutine object (type thread). coroutine.wrap(fn) creates a coroutine and returns a function that, when called, resumes it. wrap is simpler but hides the coroutine object.
-- create: returns coroutine object
local co = coroutine.create(function(x)
return x * 2
end)
local ok, val = coroutine.resume(co, 5)
print(ok, val) -- true 10
-- wrap: returns a resumable function
local gen = coroutine.wrap(function(x)
return x * 3
end)
print(gen(5)) -- 15All lessons in this course
- Creating Coroutines
- resume and yield
- Coroutine Status
- Producer-Consumer Pattern