Version 2 of Coroutines for the Dazed and Confused

Updated 2010-06-01 21:37:20 by jblz

I hope this will help others understand coroutines. A special thanks to miguel on the #tcl freenode channel for taking the time to explain this to me. Many of the words used here are his. If there any errors, i have injected them.

proc allNumbers {} {
    yield
    set i 0
    while 1 {
        yield $i
        incr i 2
    }
}

coroutine nextNumber allNumbers


for {set i 0} {$i < 10} {incr i} {
    puts "received nextNumber"
}

The first thing to understand is the yield command (which is in the coroutine's code). yield $foo acts like return $foo, but it suspends execution; when execution is resumed, the proc restarts on the line after the previous call to yield.

The procedure "allNumbers" is a proc which first calls yeild, and so suspends immediately (line 2); when it resumes it begins execution at line 3, after which it reaches another yeild within a while loop on line 5. After producing each number, it yeilds its value ... and suspends until it is called again.

Now this line:

coroutine nextNumber allNumbers

This line will (a) run allNumbers until the first yield (b) create a command called 'nextNumber' that resumes execution of allNumbers when nextNumber is called.

So after this we have allNumbers suspended right before 'set i 0', and a new command 'nextNumber' that continues it where it left off.

Get it?