views:

105

answers:

2

I want to use coroutines in actionscript to implement a state machine.

I'd like to be able to do something like the following

function stateMachine():void
{
   sendBytes(0xFFFF);
   var receiveBytes:ByteArray = yield()
   sendBytes(receiveBytes);
}

stateMachine.send( Socket.read() )

like in this blog entry

A: 

Well, how about this?

function stateMachine(socket:Socket, target:YourReceiverClass):void
{
   target.sendBytes(0xFFFF);
   var receiveByte:int = socket.readByte();
   target.sendBytes(receiveByte);
}

stateMachine( mySocket )
Simon
+1  A: 

As far as I know, Actionscript doesn't have coroutines, continuations or anything that will give you the relevant behavior (call a function without pushing a stack frame). You can fake it using static variables and a switch, but that defeats the purpose of using coroutines for state machines. Also, without tail calls (still only a proposal for ECMASCRIPT, as far as I know), faked coroutines won't use constant stack space as real coroutines do.

Regarding your sample code, coroutines generally need to loop to be useful.

outis