Skip to content
Coroutines
step 1/4

Reading — step 1 of 4

Learn

~1 min readCoroutines and Errors

A coroutine is a function you can pause and resume. Lua's only built-in concurrency primitive — cooperative, single-threaded.

local co = coroutine.create(function()
    print("step 1")
    coroutine.yield()
    print("step 2")
    coroutine.yield()
    print("step 3")
end)

coroutine.resume(co)        -- prints "step 1", pauses
coroutine.resume(co)        -- prints "step 2", pauses
coroutine.resume(co)        -- prints "step 3", finishes

Yielding values — pass data through resume/yield:

local producer = coroutine.create(function()
    for i = 1, 5 do
        coroutine.yield(i * i)
    end
end)

for _ = 1, 5 do
    local _, value = coroutine.resume(producer)
    print(value)        -- 1, 4, 9, 16, 25
end

The first return from resume is true/false (success). Subsequent returns are whatever yield passed.

coroutine.wrap — turns a coroutine into an iterator function:

local nums = coroutine.wrap(function()
    for i = 1, 10 do coroutine.yield(i) end
end)

for n in nums do print(n) end   -- works in for-in

Use cases:

  • Iterators (fancy for-in loops)
  • Generators (lazy sequences)
  • State machines
  • Cooperative scheduling (game loops, event handlers)
  • Async I/O patterns (LuaSocket, OpenResty)

Coroutines are NOT preemptive. They yield voluntarily. Lua doesn't have OS threads in its core; ecosystems (LuaJIT, Lanes) add them.

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…