Pular para o conteúdo

25 · Máquinas de Estado

Declaração e Transições

Como declarar estados, definir o estado inicial e disparar eventos com `.send`.

Nesta página

Um bloco machine lista os estados com state, indica o estado inicial com initial e declara cada transição na forma A -> B on evento. Com isso o compilador gera automaticamente o construtor e os métodos de controle — zero boilerplate.

.send("evento") tenta avançar a máquina: retorna true se a transição existia a partir do estado atual, ou false caso o evento não se aplique. O estado nunca fica inconsistente.

Semáforo com três estados; send retorna true/false conforme o evento.

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

Desafio

Adicione um quarto estado Blink e uma transição Red -> Blink on blink. Dispare light.send("blink") a partir de Red e confirme que .state muda. Depois tente disparar "blink" a partir de Green e observe o retorno false.

Veja também

Índice global

Encontre seu caminho pela Zolo

Experimente uma ideia

Comece por aqui

9 resultados

9 resultados

enespt-br