Getting started
Here is an example of pecan usage. For a more in-depth look into each of the annotated features, see the following chapters.
var factory = pecan.Co.co({ // (1)
var greeted = 0;
trace("Greeter online!");
suspend(); // (2)
while (true) { // (3)
var name = accept(); // (4)
if (name == null)
break;
trace('Hello, $name!');
yield(++greeted); // (5)
}
trace("Bye!");
}, (_ : String), (_ : Int)); // (6)
var instance = factory.run(); // (7)
// output: Greeter online!
instance.wakeup(); // (8)
instance.give("world"); // (9)
// output: Hello, world!
instance.take() == 1; // (10)
instance.give("Haxe"); // output: Hello, Haxe!
instance.take() == 2;
instance.give(null); // output: Bye!
instance.state == Terminated; // (11)
There are several things to note in the example:
(1):pecan.Co.cois one way to declare a coroutine. This is analogous to a function declaration. See declaration.(2): coroutines can be suspended and later resumed at arbitrary points, unlike regular functions, which have to run to completion. See suspending calls.(3): coroutines can make use of any Haxe syntax, even if there are suspension points within.(4)and(5):accept()andyield(...)can be used to communicate from within the coroutine in a blocking manner. See input and output.(6): input and output types (foraccept()andyield(...), respectively), must be explicitly declared. See declaration and input and output.(7): a coroutine is actually started with arun(...)call. This is analogous to a function call. See invoking.(8): coroutines suspended with asuspend()call can be resumed with awakeup()call. See suspending calls.(9)and(10):give(...)andtake()complement the coroutine I/O operations.give(...)is used to provide values to a coroutine that has calledaccept(),take()is used to take values from a coroutine that has calledyield(...).(11): see states.