gbadev.org forum archive

This is a read-only mirror of the content originally found on forum.gbadev.org (now offline), salvaged from Wayback machine copies. A new forum can be found here.

C/C++ > State machine archtecture

#5108 - sgeos - Mon Apr 21, 2003 3:58 am

I'm currently calling main like this:

[code]
int main(void)
{
void *(*fptr)(void) = main_init; /* Start state */
while (fptr = fptr()); /* Note the semicolon */
return (0);
}[/code]

You return the address of a function to change to that state. The problem with this architecture is that I can't pass data from one state to another without global variables, and that would be very useful. Any ideas?

I think my functions might need a void pointer passed in, or soemthing to that effect.

-Brendan

#5109 - tepples - Mon Apr 21, 2003 4:14 am

sgeos wrote:
You return the address of a function to change to that state. The problem with this architecture is that I can't pass data from one state to another without global variables, and that would be very useful. Any ideas?

I think my functions might need a void pointer passed in, or soemthing to that effect.

What you're dealing with is "continuations", a concept which will be familiar to those who know Scheme. You'll need to return a data structure that holds three things: a reference to the next function to be called, (optionally) the arguments to call it with, and its environment (possibly a void *).

To learn more about continuations and their implementation in C, read this
_________________
-- Where is he?
-- Who?
-- You know, the human.
-- I think he moved to Tilwick.

#5110 - sgeos - Mon Apr 21, 2003 5:05 am

tepples wrote:

You'll need to return a data structure that holds three things: a reference to the next function to be called, (optionally) the arguments to call it with, and its environment (possibly a void *).


The arguements to call a function with are of variable size. How is this dealt with? (malloc probably) What do you mean by environment?

I thought of having a state loader/saver for each funtion that stores the parameters as staic variables. (Takes a save flag and a load flag.)

-Brendan

#5111 - tepples - Mon Apr 21, 2003 6:09 am

sgeos wrote:
What do you mean by environment?

The data that would ordinarily be stored in global variables.
_________________
-- Where is he?
-- Who?
-- You know, the human.
-- I think he moved to Tilwick.