Last active
May 5, 2020 09:50
-
-
Save judah-caruso/8dee408174a536107e8f1831c9f81eb7 to your computer and use it in GitHub Desktop.
StateyMcStateMachines
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
typedef struct { | |
int counter; | |
} StateMachine; | |
typedef void* (State)(StateMachine*); | |
State* | |
second_State(StateMachine* state_machine) | |
{ | |
printf("Second state\n"); | |
// do things in state | |
return NULL; | |
} | |
State* | |
first_state(StateMachine* state_machine) | |
{ | |
printf("First state\n"); | |
// do things in state | |
return (State*)second_state; | |
} | |
int | |
main(int argc, char** argv) | |
{ | |
StateMachine state_machine = {0}; | |
State* runner = (State*)first_state; | |
while (runner != NULL) { | |
runner = (State*)(*runner)(&state_machine); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main; | |
import "core:fmt"; | |
StateMachine :: struct { | |
counter: i32 | |
} | |
State :: proc(^StateMachine) -> proc(^StateMachine); | |
second :: proc(state_machine: ^StateMachine) -> State { | |
fmt.printf("second state: %d\n", state_machine.counter); | |
state_machine.counter += 1; | |
return cast(State)first; | |
} | |
first :: proc(state_machine: ^StateMachine) -> State { | |
fmt.printf("first state: %d\n", state_machine.counter); | |
state_machine.counter += 1; | |
if state_machine.counter >= 5 { | |
return nil; | |
} | |
return cast(State)second; | |
} | |
main :: proc() { | |
state_machine := StateMachine{0}; | |
initial : State = cast(State)first; | |
for { | |
initial = cast(State)initial(&state_machine); | |
if initial == nil { | |
break; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment