Comparing Ruby Fibers to Lua Coroutines

One of the more interesting features of Lua are coroutines. One of the new features in Ruby 1.9 are fibers which are exactly the same thing, in fact they even borrowed the resume/yield method names from Lua. The following Ruby code:

   1  fib = Fiber.new do  
   2      x, y = 0, 1 
   3      loop do  
   4          Fiber.yield y 
   5          x,y = y,x+y 
   6      end 
   7  end 
   8  
   9  20.times { puts fib.resume }

is roughly equivalent to the following Lua code:

   1  fib = coroutine.create(function()
   2      local x, y = 0, 1 	
   3      while true do
   4          coroutine.yield(y)
   5          x,y = y,x+y 		
   6      end
   7  end)
   8  
   9  for i=1,20 do
  10      local _, value = coroutine.resume(fib)
  11      print(value)
  12  end