-- StateMachine.lua
local StateMachine = {}
StateMachine.__index = StateMachine
-- Create a new state machine
function StateMachine.new(character)
local self = setmetatable({}, StateMachine)
self.character = character
self.states = {}
self.currentState = nil
self.previousState = nil
self.stateData = {}
return self
end
-- Add a new state to the state machine
function StateMachine:AddState(stateName, stateConfig)
if self.states[stateName] then
warn("State", stateName, "already exists!")
return
end
self.states[stateName] = {
name = stateName,
attributes = stateConfig.attributes or {},
onEnter = stateConfig.onEnter,
onExit = stateConfig.onExit,
allowedTransitions = stateConfig.allowedTransitions or {}
}
return self
end
-- Change to a new state
function StateMachine:ChangeState(newStateName, stateData)
local newState = self.states[newStateName]
if not newState then
warn("State", newStateName, "does not exist!")
return false
end
-- Check if transition is allowed
if self.currentState then
local currentStateDef = self.states[self.currentState]
local transitionsAllowed = currentStateDef.allowedTransitions
if #transitionsAllowed > 0 and not table.find(transitionsAllowed, newStateName) then
warn("Transition from", self.currentState, "to", newStateName, "is not allowed!")
return false
end
-- Call onExit for current state
if currentStateDef.onExit then
currentStateDef.onExit(self.character, self.stateData)
end
-- Remove current state's attributes
for attrName, _ in pairs(currentStateDef.attributes) do
self.character:SetAttribute(attrName, nil)
end
end
-- Update state tracking
self.previousState = self.currentState
self.currentState = newStateName
self.stateData = stateData or {}
-- Apply attributes from new state
for attrName, attrValue in pairs(newState.attributes) do
self.character:SetAttribute(attrName, attrValue)
end
-- Call onEnter for new state
if newState.onEnter then
newState.onEnter(self.character, self.stateData)
end
return true
end
-- Get the current state name
function StateMachine:GetCurrentState()
return self.currentState
end
-- Get the previous state name
function StateMachine:GetPreviousState()
return self.previousState
end
-- Check if in a specific state
function StateMachine:IsInState(stateName)
return self.currentState == stateName
end
-- Update or add an attribute to the current state
function StateMachine:SetStateAttribute(attrName, attrValue)
if not self.currentState then
warn("No current state to set attribute on!")
return
end
local currentStateDef = self.states[self.currentState]
currentStateDef.attributes[attrName] = attrValue
-- Update the attribute on the character
self.character:SetAttribute(attrName, attrValue)
end
-- Get state-specific data
function StateMachine:GetStateData()
return self.stateData
end
-- Update state data
function StateMachine:UpdateStateData(newData)
for key, value in pairs(newData) do
self.stateData[key] = value
end
end
return StateMachine
Would you like me to explain or break down this code?