Skip to content

Declaration and Transitions

A machine block lists states with state, marks the initial state with initial, and declares each transition as A -> B on event. From that, the compiler automatically generates the constructor and control methods — zero boilerplate.

.send("event") attempts to advance the machine: it returns true if the transition existed from the current state, or false if the event does not apply. The state never becomes inconsistent.

Traffic light with three states; send returns true/false depending on the event.

01-traffic-light.zolo
Playground
// Feature: state machines — `machine` keyword, declarative transitions
// Syntax:
//   machine Name {
//       state A, B, C
//       initial A
//       A -> B on event
//   }
// `Name.new()` constructs an instance; `.state` returns the current
// state; `.send(event)` advances and returns true/false depending on
// whether the event was applicable.
// When to use: protocols, UI flows, parsers, devices with a small
// set of well-defined states. Cleaner than ad-hoc enums + match.

machine TrafficLight {
  state Red, Yellow, Green
  initial Red
  Red -> Green on go
  Green -> Yellow on caution
  Yellow -> Red on stop
}

let light = TrafficLight.new()
print(light.state)

// expected: Red

let ok = light.send("go")
print(ok)  // expected: true
print(light.state)  // expected: Green

light.send("caution")
print(light.state)  // expected: Yellow

light.send("stop")
print(light.state)  // expected: Red

// An unknown event returns false and the state stays put.
let bad = light.send("unknown")
print(bad)  // expected: false
print(light.state)  // expected: Red

Challenge

Add a fourth state Blink and a transition Red -> Blink on blink. Fire light.send("blink") from Red and confirm that .state changes. Then try firing "blink" from Green and observe the false return value.

See also

enespt-br