News for hackers. Stuff that matters.
Re:Facts about State Machines by carapace on Friday September 30, 2022 @11:42PM (#33043671)
There really isn't that much to it. E.g. in Python you can just use a dict.

    # (state, event) => (next state, action)
    FSM = {}
Add transitions (using enums):

    # Simple left down-[move*]-up sequences.
    FSM[STATE.clear,     EVENT.left_down  ] = STATE.set_caret, 'set_insertion_point'
    FSM[STATE.set_caret, EVENT.left_motion] = STATE.set_caret, 'set_insertion_point'
    FSM[STATE.set_caret, EVENT.left_up    ] = STATE.clear, 'nothing'
Then when an event happens you drive the FSM like so:

    new_state, action = FSM[state, event]
Check out https://git.sr.ht/~sforman/Xerblin/tree/trunk/item/xerblin/g... for an example.

There is also a DOT file (and SVG image) of the resulting state graph (the code to generate the DOT file directly from the FSM dict is at the bottom of the mousebindings.py file.)

There are no comments on this comment yet.