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

102 lines
2.5 KiB
Lua

local ____exports = {}
local Listeners = {}
function ____exports.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
do
local i = 0
while i < #list do
local entry = list[i + 1]
if entry.callback == callback and entry.owner == owner then
return
end
i = i + 1
end
end
list[#list + 1] = {callback = callback, owner = owner}
end
function ____exports.Off(eventName, callback, owner)
local list = Listeners[eventName]
if not list then
return
end
do
local i = #list - 1
while i >= 0 do
local entry = list[i + 1]
if entry.callback == callback and (owner == nil or entry.owner == owner) then
table.remove(list, i + 1)
end
i = i - 1
end
end
end
function ____exports.OffAllForOwner(owner)
if owner == nil then
return
end
for _, list in pairs(Listeners) do
if list ~= nil then
do
local i = #list - 1
while i >= 0 do
if list[i + 1].owner == owner then
table.remove(list, i + 1)
end
i = i - 1
end
end
end
end
end
function ____exports.Emit(eventName, ...)
local list = Listeners[eventName]
if not list then
return
end
local snapshot = {}
do
local i = 0
while i < #list do
snapshot[i + 1] = list[i + 1]
i = i + 1
end
end
do
local i = 0
while i < #snapshot do
local entry = snapshot[i + 1]
local ok
local 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
i = i + 1
end
end
end
function ____exports.Clear()
Listeners = {}
end
return ____exports