Scripted Events

Script events provide a mechanism for the game to notify running scripts when a noteworthy change in the game or UI state has occurred. Scripts can listen for events by registering lua functions to be called when a particular event occurs. When the event occurs the game calls each listener function, allowing them to respond to the change in the state of the game. Examples of available events include FactionTurnStart, PanelOpenedCampaign, CharacterCreated and ComponentLClickUp. Additionally, the game provides a context object to each listener function it calls which encapsulates information about the state change that has occured - this object may be queried in script to find out more information about the event.

Back to top

Listening for Events

The script may register a listener for an event with the core:add_listener command on the core object.

Once registered, listeners may be removed with core:remove_listener. Listeners may also be configured to stop themselves once they have triggered.

Example - FactionTurnEnd listener:

Listen for a FactionTurnEnd event for a specific faction on a specific turn.
core:add_listener(
    "faction_turn_end_listener",
    "FactionTurnEnd",
    function(context)
        return context:faction():name() == "wh_main_emp_empire" and cm:turn_number() == 7
    end,
    function()
        empire_ending_turn_seven()
    end,
    false
);
Back to top

Under the Hood

The events system is underpinned by a table called events which is created each time the script loads. This table contains many subtables, one for each event which may be triggered by the game.

The events table and related subtables may be seen in the events.lua file which lives in script folder.

By registering a listener, the script must add an element to one of these subtables that contains a function callback. When the game code wishes to trigger an event, it looks for the subtable in the events table that matches that event’s name, and calls each element within that subtable with the event context object as a single argument. To remove a listener, the script has to remove the appropriate listener entry within the appropriate subtable.

The core object provides another layer on top of this functionality which stores listeners by name, allowing them to also be removed by name, as well as a centralised interface for adding and removing listeners.

Back to top

Adding New Events

When a programmer adds a new event type, a subtable with the same name must be added in events.lua. Without it, the game will not be able to trigger the event (in this case, you will see an error message on the Lua tab of the console).

Last updated 25/08/2021 12:07:51