Skip to content

Instantly share code, notes, and snippets.

@mminer
Created March 8, 2024 18:00
Show Gist options
  • Save mminer/6e80a5e097b6c8f8ed5fe0ea8d771d8b to your computer and use it in GitHub Desktop.
Save mminer/6e80a5e097b6c8f8ed5fe0ea8d771d8b to your computer and use it in GitHub Desktop.
Simple event manager for Lua.
local eventManager <const> = {}
function addEventListener(eventName, listener)
local eventListeners = eventManager[eventName]
if not eventListeners then
eventListeners = {}
eventManager[eventName] = eventListeners
end
table.insert(eventListeners, listener)
end
function invokeEvent(eventName, ...)
local eventListeners = eventManager[eventName]
if not eventListeners then
return
end
for _, listener in ipairs(eventListeners) do
listener(...)
end
end
function removeEventListener(eventName, listener)
local eventListeners = eventManager[eventName]
if not eventListeners then
return
end
for i = 1, #eventListeners do
if eventListeners[i] == listener then
table.remove(eventListeners, i)
return
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment