Event
Event - is a single file Lua module for the Defold game engine. It provides a simple and efficient way to manage events and callbacks in your game.
Features
- Event Management: Create, subscribe, unsubscribe, and trigger events.
- Cross-Context: You can subscribe to events from different scripts.
- Callback Management: Attach callbacks to events with optional data.
- Logging: Set a logger to log event activities.
- Memory Allocations Tracker: Detects if an event callback causes a huge memory allocations.
Setup
See the Defold-Event repository on Github for the Setup, Documentation, API and Use Cases
Example
You can create a global event module that allows events to be triggered from anywhere within your game (from USE_CASES.md).
-- global_events.lua
-- Create events in the lua module
local event = require("event.event")
local M = {}
M.on_game_start = event.create()
M.on_game_over = event.create()
return M
-- Subscribe to the events from any place
local global_events = require("global_events")
local function on_game_start(self, param1, param2)
-- Animate GUI elements somehow
end
local function on_game_over(self)
-- Animate GUI elements somehow
end
function init(self)
-- The second arg - callback context is optional
-- Is will be passed as an first argument to the callback
-- Here we pass the *self* to have an access in the callbacks
global_events.on_game_start:subscribe(on_game_start, self)
global_events.on_game_over:subscribe(on_game_over, self)
end
function final(self)
-- Unsubscribe is mandatory if subscribed instance is destroyed
global_events.on_game_start:unsubscribe(on_game_start, self)
global_events.on_game_over:unsubscribe(on_game_over, self)
end
-- Trigger the events from any place
local global_events = require("global_events")
function init(self)
timer.delay(1, false, function()
global_events.on_game_start:trigger("param1", "param2")
end)
end