From: Florian Gross Date: 2003-12-20T10:20:46+09:00 Subject: Re: Could I have an example of using Continuations as 'co-routines'? Asfand Yar Qazi wrote: > Hi, Moin! > Here's my problem: instead of using setjmp/longjmp to script my game's > story-line (scripting in C++, tut-tut, what was I thinking?!), I > obviously want to use a Ruby feature, and I assume Continuations are the > thing to do it. > Anyway, could I have a simple example to start with? I did this short snipped which implements a simpler interface for Continuations to stop them from causing so much headaches for me: def Continuation.create(*args, &block) args = [args] if not args.nil? and not args.is_a? Array cc = nil result = callcc {|c| cc = c; block.call(cc) if block and args.empty?} result ||= args return *[cc, *result] end Here's a simple example of a program counting from 1 to 5 using Continuations: continuation, number = Continuation.create(1) if number <= 5 puts number continuation.call(number + 1) end And here's one showing how Continuations could be used for coroutines. However, as you may have noticed, this is quite clumsy because lots of repetitive code passages -- even if they can be factored out into something reusable I would probably still be uncertain about using Continuations for Coroutines: def give_numbers @continuation.call(true) if @continuation @continuation, done = Continuation.create(false) return 1 unless done @continuation, done = Continuation.create(false) return 2 unless done @continuation, done = Continuation.create(false) return 3 unless done @continuation = nil return 4 end give_numbers # => 1 give_numbers # => 2 give_numbers # => 3 give_numbers # => 4 give_numbers # => 1 > Thanks, > Asfand Yar Regards, Florian Gross