Review my state machine!

I’m only at the beginning of my script on the state machine but I wanted an opinion on the construction of my state machine!

type Function = (any, ...any) -> (any, ...any)

type state = {stateName: string, from: string, to: string, callback: {enter: Function, exit: Function}}

type Handle = {
	Init: string,
	
	States: {state}
} -- le but est de connecter chaque etat de State au callback

local LOWER = string.lower

local function getState(states: {state}, stateName: string): state
	for _, v in states do
		if LOWER(v.stateName) == LOWER(stateName) then
			return v
		end
	end
end

local StateMachine = {}
StateMachine.__index = StateMachine

function StateMachine.new(handle: Handle)
	assert(handle)
	
	local self = setmetatable({}, StateMachine)
	
	self.States = handle.States
	self.CurrentState = handle.Init
	self.State = getState(handle, self.CurrentState)
	
	assert(self.state)
	
	return self
end

function StateMachine.setTransition(self: self, stateName: string): ()
	local getState = getState(self.States, stateName)
	
	assert(getState)
	
	if self.State.stateName ~= getState.stateName then
		self.State.callback:exit()
		self.State = getState
		self.State.callback:enter()
	end
end

export type self = typeof(StateMachine.new(...))

return {
	new = StateMachine.new
}

2 Likes

Your state machine overall seems fine but here are a few issues that could cause runtime errors, or just not function properly:

  • In StateMachine.new, you’re calling getState on handle instead of self.States.
  • assert(self.state) should be assert(self.State).