StateMachine: immutably handle the state of things

:robot: StateMachine

Immutable finite-state machine library, where the design is basically a copy of Rust’s sm crate, but with a few additions and changes.

local StateMachine = require(game:GetService('ReplicatedStorage').StateMachine)

local Lock = StateMachine { -- Looks cool, damn!
    TurnKey = {
        Locked = 'Unlocked',
        Unlocked = 'Locked',
    },

    Break = {
        Locked = 'Broken',
        Unlocked = 'Broken',
    },
}

local lock = Lock('Locked')
lock = lock:transition('TurnKey') -- Immutable!

assert(lock:State(), 'Unlocked')
assert(lock:Trigger():Unwrap(), 'TurnKey')

Motivation

I needed an immutable state machine with something I tend to use a lot, which is the locking/unlocking logic explained in the API. Making those is pretty fun too so yeah.

If you don’t like mine, there’s this pure lua implementation and a ton more available on Wally.


Links

Install via Studio
Install via Wally
View on Github
API


Please let me know if there’s anything wrong with it!

3 Likes