Fun With Coroutines

lua-users home
wiki

This page shows some tricks using coroutines.

Print a string in reverse using coroutines

The following example reverses a string. It is implemented with coroutines and recursion (no table).

do
  local wrap, yield = coroutine.wrap, coroutine.yield

  local function putrev(w)
    if w then
      putrev(yield())
      io.write(w)
    end
  end

  function prevchar(s)
    local p = wrap(putrev)
    p"\n"
    string.gsub(s, ".", p)
    p()
  end

  -- don't look at this one until you understand the first one
  function prevword(s)
    local p = wrap(putrev)
    local function q(a, b) p(a) p(b) end
    p"\n"
    string.gsub(s, "(%S+)(%s*)", q)
    p()
  end

end

> prevchar "This is a test" 
tset a si sihT
> prevword "This is a test"
test a is This
> 

-- RiciLake

Control Inversion

Here are two different approaches at control inversion by use of coroutines:

for k in coroutine.wrap(function() table.foreach(_G, coroutine.yield) end) do
  print(k)
end

table.foreach(_G, coroutine.wrap(function(k)
  print(k)
  for k in coroutine.yield do print(k) end
end))

Alas, both don't work with stock Lua. Find out the true reasons why and you will be enlightened. Or just fetch the Coco or RVM extensions and they'll run just fine (see the mailing list for current availability).


RecentChanges · preferences
edit · history
Last edited September 17, 2008 12:47 pm GMT (diff)