Skip to content
Lua

Coroutines

Cooperative multitasking with coroutines.

By EZ4Code Team
coroutinegenerator

Code

-- Generator: yield values one at a time
function range(a, b, step)
  step = step or 1
  return coroutine.wrap(function()
    for i = a, b, step do
      coroutine.yield(i)
    end
  end)
end

for v in range(1, 10, 2) do
  print(v)  -- 1, 3, 5, 7, 9
end

-- Producer-consumer
function producer()
  for i = 1, 5 do
    coroutine.yield(i * 10)
  end
end

local co = coroutine.create(producer)
while coroutine.status(co) ~= "dead" do
  local ok, val = coroutine.resume(co)
  if val then print(val) end  -- 10, 20, 30, 40, 50
end

Explanation

Lua coroutines are cooperative (not preemptive) — they yield control explicitly. coroutine.create returns a thread; resume runs until the next yield; status checks 'suspended'/'running'/'dead'. coroutine.wrap is a convenience that returns an iterator function. Use coroutines for generators, state machines, and async patterns (Lua 5.3+ doesn't have true threads).

More Lua Snippets