F
Flash Gordon
Rui Maciel wrote, On 09/02/07 19:19:
Whether they are complicated or not can depend on what you are doing.
Yes, certainly worth doing once or twice.
A simple one could be something like:
int state = 0;
functype funcarray[] = { func1, func2, ... };
for (state = START; state != FINISHED; state = funcarray[state]())
continue;
Obviously each function returns the new state and all functions have to
have the same parameter list. Similarly a simple approach with switch is:
for ( state = START; state != FINISH; ) {
switch (state) {
case START: ... state = whatever; break;
case FRED: ... state = whatever; break;
}
}
With as much additional complexity as you require.
I know some people do not like the introduction of a state variable, but
others do not like the use of goto. You have to select the pattern that
best matches your problem, including possibly using a mixture.
The main property on which I based my definition of "best way to implement a
finite state machine" was code simplicity to write, read, debug, modify. As
far as I can tell the end result may end up being clearer and simpler to
deal with than a whole bunch of convoluted if/switch nests peppered with
loops.
Whether they are complicated or not can depend on what you are doing.
I see what you mean. When I started this project first I delved into Ragel
but as I'm mainly interested in the learning experience and I never wrote a
FSM before, I found it best to try to write it by hand.
Yes, certainly worth doing once or twice.
That sounds very interesting. Where can I learn more about those approaches,
specially the one that uses table-and-function-pointers?
A simple one could be something like:
int state = 0;
functype funcarray[] = { func1, func2, ... };
for (state = START; state != FINISHED; state = funcarray[state]())
continue;
Obviously each function returns the new state and all functions have to
have the same parameter list. Similarly a simple approach with switch is:
for ( state = START; state != FINISH; ) {
switch (state) {
case START: ... state = whatever; break;
case FRED: ... state = whatever; break;
}
}
With as much additional complexity as you require.
I know some people do not like the introduction of a state variable, but
others do not like the use of goto. You have to select the pattern that
best matches your problem, including possibly using a mixture.