Skip to content
Tutorials Center
My learning

Topics

Lesson 29 of 32 ยท Projects

Project: A Tiny Event Emitter and Scheduler

Build an event emitter with closures and a cooperative scheduler that runs coroutines as timed tasks in Lua, with a JavaScript stand-in running a virtual clock.

Games, servers and user interfaces all share a problem: many things happen "at the same time", and the code has to stay readable. Two small tools solve most of it. An event emitter lets one part of a program announce that something happened without knowing who is listening. A scheduler lets several tasks take turns, each pausing for a while and then continuing where it stopped.

Lua gives you exactly the ingredients: functions are values (callbacks), closures remember their surroundings (unsubscribe handles), and coroutines can pause in the middle of a function (tasks). In this project you build both tools in under 100 lines and connect them. The real Lua is read-only because this site cannot run Lua; the runnable code is a JavaScript stand-in, with generators in the role of coroutines and a virtual clock so that waiting takes no real time and the output is the same on every run. If you need a refresher, see varargs and closures and coroutines.

Two tools, one project

Emitter Announce events without knowing the listeners.
Scheduler Let tasks take turns and sleep.

Callbacks react; coroutines wait.

1 / 2

Step 1: the event emitter

The emitter keeps a table that maps an event name to a list of handler functions. on adds a handler and returns a function that removes it, which is a closure over the list and the handler. emit calls every handler with the extra arguments.

LUA
local function newEmitter()
  local handlers = {}
  local emitter = {}

  function emitter.on(name, fn)
    local list = handlers[name]
    if not list then
      list = {}
      handlers[name] = list
    end
    list[#list + 1] = fn

    return function()              -- unsubscribe handle
      for i, f in ipairs(list) do
        if f == fn then
          table.remove(list, i)
          return true
        end
      end
      return false
    end
  end

  function emitter.once(name, fn)
    local off
    off = emitter.on(name, function(...)
      off()
      return fn(...)
    end)
    return off
  end

  function emitter.emit(name, ...)
    local list = handlers[name]
    if not list then
      return 0
    end
    local snapshot = table.move(list, 1, #list, 1, {})
    for _, fn in ipairs(snapshot) do
      local ok, err = pcall(fn, ...)
      if not ok then
        print("handler error: " .. tostring(err))
      end
    end
    return #snapshot
  end

  return emitter
end

Study three decisions, because each one prevents a real bug:

  • emit loops over a snapshot. A handler may unsubscribe itself (that is exactly what once does). If emit iterated the live list, table.remove would shift the remaining handlers down and the loop would skip one. Copying the list with table.move first makes the iteration safe.
  • Each call uses pcall. One broken handler should not stop the others from hearing the event. The error is reported and the loop moves on.
  • once is built from on. The wrapper calls off() before running the real handler, and it uses ... to forward every argument. The local off is declared first so that the wrapper can see it.

The first stand-in is the same emitter in JavaScript. Rest parameters (...args) play the part of Lua's ....

JS Stand-in: the event emitter

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Read the output closely. The once handler ran for Ana only. Ben's score of 500 made handler B throw, yet the error was reported without stopping anything else. After offScore(), only B remained.

Step 2: tasks as coroutines

A task is a coroutine that calls wait(seconds) whenever it wants to sleep. wait is just coroutine.yield(seconds): it hands the delay to the scheduler and pauses. The scheduler keeps a queue of sleeping tasks, each with the time it should wake. It repeatedly picks the one that wakes first, moves the clock to that time, and resumes it.

flowchart TD
  A["Queue not empty?"] -->|yes| B["Pick earliest wake time"]
  B --> C["Set clock to that time"]
  C --> D["Resume the task"]
  D --> E{"Task finished?"}
  E -->|no| F["Queue it again at clock + delay"]
  E -->|yes| G["Drop the task"]
  F --> A
  G --> A
  A -->|no| H["Stop"]

The run loop: the clock jumps from event to event, so waiting costs no real time.

LUA
local function newScheduler()
  local now = 0
  local seq = 0
  local queue = {}
  local sched = {}

  local function push(time, co)
    seq = seq + 1
    queue[#queue + 1] = { time = time, seq = seq, co = co }
  end

  function sched.clock()
    return now
  end

  function sched.wait(seconds)
    return coroutine.yield(seconds)
  end

  function sched.spawn(fn, ...)
    local args = table.pack(...)
    local co = coroutine.create(function()
      fn(table.unpack(args, 1, args.n))
    end)
    push(now, co)
  end

  function sched.after(delay, fn)
    sched.spawn(function()
      sched.wait(delay)
      fn()
    end)
  end

  function sched.every(interval, times, fn)
    sched.spawn(function()
      for i = 1, times do
        sched.wait(interval)
        fn(i)
      end
    end)
  end

  function sched.run()
    while #queue > 0 do
      table.sort(queue, function(a, b)
        if a.time ~= b.time then
          return a.time < b.time
        end
        return a.seq < b.seq
      end)
      local entry = table.remove(queue, 1)
      now = entry.time
      local ok, delay = coroutine.resume(entry.co)
      if not ok then
        print("task error: " .. tostring(delay))
      elseif coroutine.status(entry.co) ~= "dead" then
        push(now + delay, entry.co)
      end
    end
  end

  return sched
end

The details again matter. The queue is sorted by time and then by seq, a counter that grows with every push. Two tasks that wake at the same moment therefore always run in the order they were queued, which makes the program deterministic; without seq, the unstable table.sort could swap them. Resuming a coroutine returns true plus whatever it yielded, so delay is the number of seconds the task asked to sleep. A task that raised an error comes back as false plus the message, and the scheduler reports it and carries on with the other tasks. sched.spawn uses table.pack and table.unpack(args, 1, args.n) so arguments that are nil survive the trip.

Sorting the whole queue on every step is simple and fine for a small program. A real scheduler would use a heap, as in the priority queues lesson in the DSA tutorial.

Step 3: connect the two

The scheduler tells the emitter when to announce things, and handlers may start new tasks. Here is the plan we run in the stand-in below, in Lua terms:

LUA
local bus = newEmitter()
local sched = newScheduler()

local function log(message)
  print(string.format("[t=%.1f] %s", sched.clock(), message))
end

bus.on("tick", function(n) log("tick " .. n) end)
bus.once("done", function(who) log(who .. " finished") end)

sched.every(1, 3, function(n) bus.emit("tick", n) end)

sched.spawn(function()
  log("worker started")
  sched.wait(1.5)
  log("worker halfway")
  sched.wait(1.5)
  bus.emit("done", "worker")
  bus.emit("done", "worker")   -- the once handler is already gone
end)

sched.after(2.5, function() log("alarm!") end)

sched.run()

In JavaScript, a generator function stands in for a coroutine: yield 1.5 is sched.wait(1.5). The run loop is the same one as above, written with the same sorting rule.

JS Stand-in: emitter and scheduler together

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Check the timeline. The task that throws at t=0.5 is reported and the others never notice. Ticks arrive at 1.0, 2.0 and 3.0, the worker speaks at 0, 1.5 and 3.0, and the alarm fires at 2.5. At t=3.0 two tasks are due together: the worker was queued back at 1.5 and the third tick at 2.0, so the seq counter makes the worker run first and the order is the same on every run. The second done emission reaches nobody, because once removed its handler after the first.

Cooperative scheduling means a task only gives up control when it calls wait. A task that loops forever without waiting would freeze every other task, because nothing can interrupt a coroutine from outside. Keep tasks short between waits.

Ideas to extend it

  • Add sched.cancel(handle): make spawn return an id and skip cancelled tasks when they come off the queue.
  • Let wait return the elapsed virtual time, so a task can compute how late it was woken.
  • Add emitter.off(name) to drop every handler for an event, and emitter.count(name) for tests.
  • Use os.clock() and a real sleep in the host to turn the virtual clock into a real timer loop.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why does emit iterate over a snapshot of the handler list?

    table.remove shifts later entries down. Looping over the live list while removing from it would skip the handler that moved into the removed slot.
  2. 2. What does sched.wait(seconds) do inside a task?

    wait is coroutine.yield(seconds). The coroutine pauses, and the scheduler decides when to resume it.
  3. 3. What is the seq field in the queue entries for?

    table.sort is not stable. Sorting by time and then by an increasing sequence number gives a deterministic order for ties.
  4. 4. Why is coroutine.resume's first return value checked with ok in sched.run?

    resume returns true plus the yielded or returned values, or false plus the error message, so the scheduler can report a failed task and keep going.

Summary

  • An emitter is a table from event names to lists of functions; on returns a closure that unsubscribes.
  • Iterate over a snapshot in emit and call handlers with pcall so changes and errors do not disturb the others.
  • A task is a coroutine; wait(n) is coroutine.yield(n).
  • The scheduler repeatedly picks the earliest wake time, advances a virtual clock and resumes the task.
  • Break ties with an increasing sequence number because table.sort is not stable.
  • Tasks are cooperative: they must yield to let others run.

Next: Exercises with Solutions