Lesson 1 of 10
An event system
- 14 min
- 6 checks
- 3 hints
- Go to task
Goal
Subscribe with on and fire with emit
Explanation
Game scripts don't call each other directly. They talk through events. A player joining, a player running out of health, an item being picked up: each of these is an event that gets fired, and whoever cares about it listens. That's how AddEventHandler and TriggerEvent work in FiveM, and :Connect and :Fire in Roblox.
A single table is all you need to build this system. Its keys are event names and its values are lists of listener functions: on adds a function to a list, and emit walks through the functions and calls each one with the arguments.
The three dots ... in Lua mean “every argument that was passed in”, and you pass them along unchanged like this: handler(...).
Your task
Write on(name, handler) and emit(name, ...) so that one event can have several listeners, called in the order they were added, and so that an event with no listeners doesn't throw an error.
Checks
6 checks- The on and emit functions are defined
- The listener is called with the argument
- Several listeners are called in order
- Every argument reaches the listener
- An event with no listeners doesn't throw an error
- The example printed the greeting