31
31
current_state string
32
32
}
33
33
34
+ // StateMachine static method returns a new StateMachine instance.
34
35
pub fn new () StateMachine {
35
36
return StateMachine{}
36
37
}
37
38
39
+ // set_state sets the current state of the state machine to the given state by `name`.
38
40
pub fn (mut s StateMachine) set_state (name string ) ! {
39
41
if name in s.states {
40
42
s.current_state = name
@@ -43,10 +45,13 @@ pub fn (mut s StateMachine) set_state(name string) ! {
43
45
}
44
46
}
45
47
48
+ // get_state returns the current state of the state machine.
46
49
pub fn (mut s StateMachine) get_state () string {
47
50
return s.current_state
48
51
}
49
52
53
+ // add_state adds a new state to the state machine.
54
+ // It takes the `name` of the state, and three event handlers: `entry`, `run`, and `exit`.
50
55
pub fn (mut s StateMachine) add_state (name string , entry EventHandlerFn, run EventHandlerFn, exit EventHandlerFn) {
51
56
s.states[name] = State{
52
57
entry_handler: entry
@@ -58,6 +63,8 @@ pub fn (mut s StateMachine) add_state(name string, entry EventHandlerFn, run Eve
58
63
}
59
64
}
60
65
66
+ // add_transition adds a new transition to the state machine.
67
+ // It takes the `from` and `to` states, and a condition handler.
61
68
pub fn (mut s StateMachine) add_transition (from string , to string , condition_handler ConditionFn) {
62
69
t := Transition{
63
70
to: to
@@ -70,6 +77,7 @@ pub fn (mut s StateMachine) add_transition(from string, to string, condition_han
70
77
s.transitions[from] = [t]
71
78
}
72
79
80
+ // run runs the state machine. It takes a `receiver` argument that is passed to the event handlers.
73
81
pub fn (mut s StateMachine) run (receiver voidptr ) ! {
74
82
from_state := s.current_state
75
83
mut to_state := s.current_state
0 commit comments