Finite-state machine

Share the finished AutoHotkey v2 Scripts and libraries you made here. Please put the current version of AutoHotkey v2 you used in Square Brackets at the start of the topic title.
oif2003
Posts: 213
Joined: 17 Oct 2018, 11:43
GitHub: oif2003

Finite-state machine

05 Aug 2019, 06:15

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

Return to “AutoHotkey v2 Scripts and Functions”

Who is online

Users browsing this forum: No registered users and 1 guest