Lesson 5 of 10

A state machine

Goal

Clear transitions with enter and exit hooks

01

Explanation

The guard in your game is either idle, chasing or attacking, and never in two of those at once. A state machine says this explicitly: the guard has exactly one state at any moment, and each state has a table of the states it's allowed to move to, so the guard can't go straight from idle to attacking. It has to chase first.

Many games start out instead with scattered booleans like isChasing and isAttacking, and then a guard shows up that chases and attacks at the same moment because some line forgot to switch one of them off. Each state also has two optional hooks: enter starts the state's animation or sound when the guard enters it, and exit cleans up whatever the state started when the guard leaves it.

Mind the order. Check that the transition is allowed before you call any hook, because if you call exit and only then find out the transition isn't allowed, you leave the guard in the attack state with his sword already sheathed. Then call the old state's exit before the new state's enter, or the old state will clean up what the new one has just started.

02

Your task

Complete StateMachine:go(to). If to isn't in the current state's to table, return false without calling anything. Otherwise call the old state's exit if it has one, then change self.state, then call the new state's enter if it has one, and return true.

Checks

6 checks
  1. An allowed transition changes the state
  2. A forbidden transition returns false and the state stays the same
  3. A forbidden transition doesn't call any hook
  4. The old state's exit is called before the new state's enter
  5. The state changes between the two hooks
  6. Both hooks are optional
03

Hints

0/3
main.lua
OutputLua 5.4 (wasmoon)

Loading Lua.

–/6

Checks start once the environment is ready.

6 checks listed under “Your task”.