0Pricing
Lua Academy · Lesson

Event Systems in Lua

Build a lightweight event dispatcher with callbacks stored in tables.

Why Event Systems?

An event system decouples producers (things that fire events) from consumers (things that react). In Lua, it is easily built with tables of callback functions.

Simple Event Dispatcher

A dispatcher stores lists of listeners keyed by event name.

local EventEmitter = {}
EventEmitter.__index = EventEmitter

function EventEmitter.new()
  return setmetatable({_listeners = {}}, EventEmitter)
end

function EventEmitter:on(event, fn)
  self._listeners[event] = self._listeners[event] or {}
  table.insert(self._listeners[event], fn)
end

function EventEmitter:emit(event, ...)
  for _, fn in ipairs(self._listeners[event] or {}) do
    fn(...)
  end
end

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