Coroutines: Cooperative Multitasking
A coroutine is an independent thread of execution that you can pause and resume by hand, unlike OS threads, only one coroutine (or the main program) ever runs at a time, so there's no race condition to worry about.
Creating and resuming a coroutine
coroutine.create(fn)builds a coroutine without running it yet.coroutine.resume(co, ...)starts/continues it, passing...in as arguments (either to the function itself, the first time, or ascoroutine.yield's return value on later resumes).coroutine.yield(...)pauses the coroutine and hands...back to whoever calledresume.coroutine.status(co)reports"suspended","running","normal", or"dead".
A generator built on coroutines
coroutine.wrap is coroutine.create plus automatic resume calls, wrapped in a plain function you can call directly (or use in a for ... in loop), it's the idiomatic way to build a lazy generator/iterator in Lua.
WARNING
Unlike pcall, an error raised inside a coroutine created with coroutine.wrap propagates as a normal Lua error to the caller of the wrapped function. A coroutine made with plain coroutine.create, by contrast, reports the error as its second resume return value instead of raising it, check coroutine.resume's boolean result if you use create directly.