for my state machine i not use number for state value, i used boolean, but for me is better use boolean that number
please post your opinion !
export type statesList = {[string]: boolean}
export type funcList = {[string]: (bool, any, ...any) -> (any, ...any)}
export type state = {
state: string,
value: boolean
}
local StateMachine = {}
StateMachine.__index = StateMachine
function StateMachine.new(statesList: statesList, funcList: funcList)
local self = setmetatable({}, StateMachine)
self.current = nil
self.statesList = statesList
self.funcList = funcList
self.isProcess = false
for index, value in self.statesList do
if not value then continue end
self.current = {
state = index,
value = value
}
end
assert(self.current, "Failed to set current state")
return self
end
function StateMachine:setNewState(new: string, beforeStateArgs: {any}, newStateArgs: {any})
if self.isProcess then return end
assert(new and new.state and new.value, "Failed to set new state !")
assert(self.current.state ~= new.state, "currentState == "..new.state)
assert(type(new.value) == "boolean", "value of "..new.state.." is not boolean value")
assert(new.value, "your value is not true.")
assert(self.funcList[new.state] and self.funcList[self.current.state], "not function founded..")
self.isProcess = true
self.current.value = false
self.funcList[self.current.state](self.current.value, beforeStateArgs)
self.funcList[new.state](new.value, newStateArgs)
self.current = new
self.isProcess = false
end
return StateMachine
local stateMachine = require(game.ReplicatedStorage.StateMachine)
local function onOpen(bool, args: {any})
if bool then
print("Open state starting")
else
print("Open state Closing")
end
end
local function onClose(bool, args: {any})
if bool then
print("Close state starting")
else
print("Close state Closing")
end
end
local stateList = {
["Open"] = false,
["Close"] = true
}
local funcList = {
["Open"] = onOpen,
["Close"] = onClose
}
local newState = stateMachine.new(stateList, funcList)
newState:setNewState({state = "Open", value = true})
task.wait(5)
newState:setNewState({state = "Close", value = true})