[statemachine] add AnyState, support transition trigger from any state

This commit is contained in:
Eric Mastro 2023-02-17 15:46:12 +11:00
parent cfe6693268
commit 59576e76d8
No known key found for this signature in database
GPG Key ID: AD065ECE27A873B9
2 changed files with 3 additions and 2 deletions

View File

@ -19,6 +19,7 @@ type
errored*: TransitionProperty[bool]
lastError*: ref CatchableError
State* = ref object of RootObj
AnyState* = ref object of State
Event* = proc(state: State): ?State {.gcsafe, upraises:[].}
TransitionCondition* = proc(machine: Machine, state: State): bool {.gcsafe, upraises:[].}
Transition* = object of RootObj
@ -50,7 +51,7 @@ proc schedule*(machine: Machine, event: Event) =
proc checkTransitions(machine: Machine) =
for transition in machine.transitions:
if transition.trigger(machine, machine.state) and
(machine.state == nil or machine.state == transition.prevState):
(machine.state == nil or machine.state == transition.prevState or transition.prevState of AnyState):
machine.schedule(Event.transition(machine.state, transition.nextState))
proc setValue*[T](prop: TransitionProperty[T], value: T) =

View File

@ -69,7 +69,7 @@ suite "async state machines":
MyMachine(m).requestFinished.value
),
Transition.new(
state6,
AnyState.new(),
state5,
proc(m: Machine, s: State): bool =
MyMachine(m).errored.value