FSM
The FSM module provides a set of classes for creating finite state machines.
Example
The following code demonstrates the usage of the FSM module.
local MyModule = select(2, ...).MyModule
local FSM = MyModule:From("LibTSMUtil"):Include("FSM")
local fsm = FSM.New("ENEMY_NPC")
:AddState(FSM.NewState("ST_PATROLLING")
:SetOnEnter(function(context)
context.health = 100
end)
:AddTransition("ST_ATTACKING")
:AddEventTransition("EV_AGROED", "ST_ATTACKING")
)
:AddState(FSM.NewState("ST_ATTACKING")
:SetOnEnter(function(context)
print("I'm coming after you!")
end)
:AddTransition("ST_DEAD")
:AddTransition("ST_PATROLLING")
:AddEventTransition("EV_DEAGRO", "ST_PATROLLING")
:AddEvent("EV_DAMAGE", function(context, damage)
context.health = context.health - damage
if context.health <= 0 then
return "ST_DEAD"
end
end)
)
:AddState(FSM.NewState("ST_DEAD")
:SetOnEnter(function(context)
print("Argh!")
end)
:AddTransition("ST_PATROLLING")
:AddEventTransition("EV_RESPAWN", "ST_PATROLLING")
)
:Init("ST_PATROLLING", {health = 100})
fsm:ProcessEvent("EV_AGROED") -- print: I'm coming after you!
fsm:ProcessEvent("EV_DAMAGE", 70)
fsm:ProcessEvent("EV_DAMAGE", 40) -- print: Argh!
fsm:ProcessEvent("EV_RESPAWN")
API
-
class FSM:
LibTSMModule
-
class FSMObject:
Class -
staticmethod New(name:
string):FSMObject Creates a new FSM object.
- Parameters:
name (
string) – The name of the FSM (for debugging)
-
AddState(self:
FSMObject, stateObj:FSMState):FSMObject Add an FSM state.
- Parameters:
stateObj (
FSMState) – The FSM state object to add
-
Init(self:
FSMObject, initialState:string, context?:table):FSMObject Initialize the FSM.
- Parameters:
initialState (
string) – The name of the initial statecontext? (
table) – The FSM context table which gets passed to all state and event handlers
-
staticmethod New(name:
-
class FSMState:
Class -
staticmethod New(name:
string):FSMState Create a new FSM state.
- Parameters:
name (
string) – The name of the state
-
SetOnEnter(self:
FSMState, handler:function):FSMState Set the OnEnter handler.
This function is called upon entering the state.
- Parameters:
handler (
function) – The handler function to call
-
SetOnExit(self:
FSMState, handler:function):FSMState Set the OnExit handler.
This function is called upon existing the state.
- Parameters:
handler (
function) – The handler function to call
-
AddTransition(self:
FSMState, toState:string):FSMState Add a transition.
- Parameters:
toState (
string) – The state this transition goes to
-
staticmethod New(name: