Page 1 of 1

Finite-state machine

Posted: 05 Aug 2019, 06:15
by oif2003
Hi,

I wrote this script as an exercise while learning about finite-state machine (https://en.wikipedia.org/wiki/Finite-state_machine). I find it useful because it seems like a cleaner way to model certain problems. As you can see in my attempt to simulate the operations of a microwave, the state diagram can be directly translated into code. Depending on the situation, this approach can make coding easier by avoiding the excessive use of if-statements. This is my first attempt and I imagine it could be done better. Any feedback is welcomed!

Code: Select all

class simpleStateMachine {
	__New(state) => (this.state := state, this)
	changeState(state) => this.state := state
	dispatch(functionName, parameters*) {
		try
			return (this)["state_" this.state][functionName](this, parameters*)
		catch	;output errors here.  nothing happens if method is not defined.  change this behavior as necessary
			return (FileAppend("Error calling " fname " in state_" this.state " (Line " Exception("", -1).Line ")`n", "*"), this.state) 
	}	
	
	class state_1 {
		transition_from_1_to_2(_this) => _this.changeState(2)
		transition_from_1_to_3(_this) => _this.changeState(3)
	}
	
	class state_2 {
		transition_from_2_to_1(_this) => _this.changeState(1)
		transition_from_2_to_3(_this) => _this.changeState(3)
	}
	
	class state_3 {
		transition_from_3_to_1(_this) => _this.changeState(1)
		transition_from_3_to_2(_this) => _this.changeState(2)
	}
}

myStateMachine := new simpleStateMachine(initial_state := 1)
MsgBox("Initialized myStateMachine w/ state = " myStateMachine.state)
MsgBox("... current state of myStateMachine = " myStateMachine.dispatch("transition_from_1_to_2")) 
MsgBox("... current state of myStateMachine = " myStateMachine.dispatch("transition_from_2_to_3")) 
MsgBox("... current state of myStateMachine = " myStateMachine.dispatch("transition_from_3_to_1"))

Here is the state diagram for a simple microwave:
Spoiler

My attempt to turn the above diagram into code. The circles represent the states, and the arrows represent the transitions, which are translated into methods under each corresponding state.
Spoiler