Skip to content
Lua

Coroutines

Multitarefa cooperativa com coroutines.

#coroutine#generator

Code

lua
-- 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