Fun With Coroutines

lua-users home
wiki

Showing revision 5

Print a string in reverse without using a 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

Two different approaches at control inversion:

  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 · current revision
Edited August 24, 2005 10:08 pm GMT (diff)