util.events

Quite a common desire is to allow code to be notified when a particular event happens elsewhere in the code. This library abstracts that design pattern.

Usage

   -- Step 1: Create the events object (happens just once)
   local events = require "util.events";
   local myevents = events.new();
 
   -- Step 2: A watcher adds a handler to know when we are poked
   local function on_poke(data) print("Oh no, I was poked by "..data.."!"); end
   myevents.add_handler("poked", on_poke);
 
   -- Step 3: A poker pokes... passing some data to the handlers
   myevents.fire_event("poked", "a vicious poker");

This simple example demonstrates the 3 primary ways of interacting with an events object, below follows a reference to each of the methods.

Reference

Module

events.new()

Returns a new events object. This object supports methods for adding handlers for, and firing, events.

Events objects

These methods exist on objects returned by the above events.new().

events.fire_event(name, data)

Fire the event with the given name, passing the optional data to all handlers.

Should any callback for an event return a value other than nil then fire_event() will stop calling further callbacks return this value.

events.add_handler(name, callback, priority)

When the event specified by 'name' is fired the function specified by 'callback' will be called.

Callbacks are called in an unspecified order, except that callbacks with a higher 'priority' are executed first. If not given, the priority defaults to 0.

A callback should return nothing, or nil, to continue processing of other callbacks. Should it return any other value then further callbacks shall not be called, and the value will be returned to the code that fired the event.

events.remove_handler(name, callback)

Remove the given handler for the specified event. It shall no longer be called when the event is fired.

events.set_debug_hook(hook_function)

Sets the given function as the active debug hook function. Returns the previous active hook, or nil if no debug hook was active.

To remove an existing hook, pass nil.

The hook function gets called whenever an event handler would be called. It is the responsibility of the hook function to call the handler.

The hook_function should be a function that accepts three parameters, handler (the event handler to be called), event_name (the name of the event), and event_data (the data to be passed to the handler).

A minimal valid hook function would be:

local function hook_function (handler, event_name, event_data)
    return handler(event_data);
end