News for hackers. Stuff that matters.
Re:Facts about State Machines by ww520 on Friday September 30, 2022 @07:24PM (#33042003)
There're different ways to implement a state machine, table-driven, object-driven, function pointer driven, callback based, etc. If you just want a simple and hard coded sate machine, nothing beats switch statements. You can do something like the following.

    enum State { S1, S2, S3, S4, ... , END }
    
    State transition(State current_state, int input) {
        switch current_state
            case S1:
                switch input
                    case 100: new_state = S3
                              do_action1()
                    case 101: new_state = S4
                              do_action2()
                    default:  error()
            case S2:
                switch input
                    case 100: new_state = S3
                              do_action3()
                    case 206: new_state = S11
                              do_action4()
                    case 207: new_state = S12
                              do_action5()
                    case 208: new_state = S19
                              do_action6()
                    default:  error()
            case S3:
                switch input
                    ...
            ...
    
         return new_state
    }

    run_state_machine(int[] inputs) {
        State state = S1
        foreach input in inputs
            state = transition(state, input)

    }
That's it. It's simple to understand and it's clear what the legal transitions are from each state based on the input. You can attach actions and data update on each state transition to do something useful.

There are no comments on this comment yet.