Files
UnrealLuaDemo/Content/Script/Framework/EventBus.lua
T

94 lines
2.2 KiB
Lua
Raw Normal View History

---@class Framework.EventBus
---Lightweight publish/subscribe event bus for decoupled Lua game systems.
local EventBus = {}
local Listeners = {}
---@param eventName string
---@param callback function
---@param owner any|nil
function EventBus.On(eventName, callback, owner)
assert(type(eventName) == "string", "EventBus.On: eventName must be a string")
assert(type(callback) == "function", "EventBus.On: callback must be a function")
local list = Listeners[eventName]
if not list then
list = {}
Listeners[eventName] = list
end
for _, entry in ipairs(list) do
if entry.callback == callback and entry.owner == owner then
return
end
end
list[#list + 1] = {
callback = callback,
owner = owner,
}
end
---@param eventName string
---@param callback function
---@param owner any|nil
function EventBus.Off(eventName, callback, owner)
local list = Listeners[eventName]
if not list then
return
end
for i = #list, 1, -1 do
local entry = list[i]
if entry.callback == callback and (owner == nil or entry.owner == owner) then
table.remove(list, i)
end
end
end
---@param owner any
function EventBus.OffAllForOwner(owner)
if owner == nil then
return
end
for _, list in pairs(Listeners) do
for i = #list, 1, -1 do
if list[i].owner == owner then
table.remove(list, i)
end
end
end
end
---@param eventName string
function EventBus.Emit(eventName, ...)
local list = Listeners[eventName]
if not list then
return
end
-- Snapshot to allow listeners to unsubscribe during dispatch
local snapshot = {}
for i = 1, #list do
snapshot[i] = list[i]
end
for i = 1, #snapshot do
local entry = snapshot[i]
local ok, err
if entry.owner ~= nil then
ok, err = pcall(entry.callback, entry.owner, ...)
else
ok, err = pcall(entry.callback, ...)
end
if not ok then
print(string.format("[UnrealLuaDemo][ERROR] EventBus(%s): %s", eventName, tostring(err)))
end
end
end
function EventBus.Clear()
Listeners = {}
end
return EventBus