Lua Academy · Lesson

AI Behavior with State Machines

Implement FSM-based enemy AI logic entirely in Lua scripts.

Lesson 3 of 413 steps

AI Behavior with State Machines is a free Lua Academy lesson on CoddyKit. This is lesson 3 of 4. Any 3 lessons of this learning path are free to read in full — after that, CoddyKit PRO unlocks every lesson, plus hands-on practice with a built-in code editor and a 24/7 AI tutor. It is part of the Lua Academy learning path, and your progress syncs across the web and the CoddyKit app. The Lua Academy course includes 4 lessons in total.

What Is a Finite State Machine?

A Finite State Machine (FSM) defines behavior as a set of states with transitions between them triggered by conditions or events.

FSM Table Structure

Represent an FSM as a table with a current state, a states table, and optional enter/exit/update callbacks per state.

local function newFSM(initialState)
  return {
    current = initialState,
    states  = {},
  }
end

Defining States

Each state is a table with optional enter, update, and exit functions.

local fsm = newFSM("idle")
fsm.states.idle = {
  enter  = function(self) print("Enter idle") end,
  update = function(self, dt)
    if self.enemy then self:transition("chase") end
  end,
  exit   = function(self) print("Exit idle") end
}

Adding the Chase State

The chase state pursues the player and transitions to attack when close enough.

fsm.states.chase = {
  enter = function(self) print("Chasing!") end,
  update = function(self, dt)
    if self.distToPlayer < 2 then
      self:transition("attack")
    elseif not self.enemy then
      self:transition("idle")
    end
  end
}

Transition Function

A transition calls exit on the current state, changes state, then calls enter on the new state.

function fsm:transition(newState)
  local cur = self.states[self.current]
  if cur and cur.exit then cur:exit() end
  self.current = newState
  local next = self.states[newState]
  if next and next.enter then next:enter() end
end

Updating the FSM

Each game tick call fsm:update(dt) to run the current state's update logic.

function fsm:update(dt)
  local state = self.states[self.current]
  if state and state.update then
    state:update(dt)
  end
end

Hierarchical State Machines

States can contain nested FSMs. A parent state handles broad behavior (combat vs. patrol) while child FSMs handle details within each parent state.

Data-Driven FSMs

Define FSM transitions as data tables loaded from config files. This lets designers tweak AI without touching code.

local transitions = {
  idle  = {seeEnemy = "chase"},
  chase = {lostEnemy = "idle", nearEnemy = "attack"},
  attack = {enemyDead = "idle"},
}

Stacked State Machines

A state stack allows temporary states (e.g., "stunned") to push on top of the current state and resume it when done.

Multiple AI Agents

Each enemy entity has its own FSM instance, so their AI runs independently. This is easy with Lua tables and closures.

Debugging FSM

Log all transitions during development. A trace table stores {from, to, time} for post-mortem analysis of AI behavior.

FSM Question

What triggers a state transition in an FSM?

Recap: AI with State Machines

Lua FSMs use a table of state objects (enter/update/exit) with a transition function. They cleanly separate AI concerns, support data-driven design, and scale from simple enemy brains to complex hierarchical behavior trees.

Free to start

Learn Lua with an AI tutor — free

Write and run real code in your browser, get instant help from a 24/7 AI tutor, and pick up where you left off on the web or in the app.

Courses
40
Lessons
159

Frequently Asked Questions

Is the “AI Behavior with State Machines” lesson free?

Yes — any 3 lessons of the Lua Academy learning path, including “AI Behavior with State Machines”, are free to read in full here on the web. After that, CoddyKit PRO unlocks every lesson, plus interactive practice with a built-in code editor and a 24/7 AI tutor. The Lua Academy course includes 4 lessons in total.

What will I learn in “AI Behavior with State Machines”?

Implement FSM-based enemy AI logic entirely in Lua scripts. You practise Lua Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Lua Academy?

No prior experience is required. Lua Academy on CoddyKit is structured for beginners through advanced learners, so you can start here or from the beginning and move at your own pace. This is lesson 3 of 4.

How long does the “AI Behavior with State Machines” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Lua Academy lesson?

Yes. Every Lua Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Event Systems in Lua
  2. Component-Based Scripting
  3. AI Behavior with State Machines
  4. Data-Driven Config and Hot-Reload
← Back to Lua Academy