2023-10-17 17:19:35 +00:00
|
|
|
local modname = minetest.get_current_modname()
|
|
|
|
|
|
|
|
blockgame.events = blockgame.events or {}
|
|
|
|
local api = blockgame.events
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
local namespaces = {}
|
|
|
|
|
|
|
|
function api.namespace (name)
|
|
|
|
if namespaces[name] then return namespaces[name] end
|
|
|
|
namespaces[name] = {
|
|
|
|
listen = function (...) return api.listen(name, ...) end,
|
|
|
|
broadcast = function (...) return api.broadcast(name, ...) end,
|
2023-10-17 18:38:43 +00:00
|
|
|
listeners = {},
|
2023-10-17 17:19:35 +00:00
|
|
|
}
|
|
|
|
return namespaces[name]
|
|
|
|
end
|
|
|
|
|
|
|
|
function api.listen (namespace_name, event, callback)
|
2023-10-17 18:38:43 +00:00
|
|
|
local listeners = api.namespace(namespace_name).listeners
|
|
|
|
listeners[event] = listeners[event] or {}
|
2023-10-17 17:19:35 +00:00
|
|
|
|
2023-10-17 18:38:43 +00:00
|
|
|
table.insert(listeners[event], {
|
2023-10-17 17:19:35 +00:00
|
|
|
event = event,
|
|
|
|
callback = callback,
|
|
|
|
})
|
2023-10-17 18:38:43 +00:00
|
|
|
return #listeners[event]
|
2023-10-17 17:19:35 +00:00
|
|
|
end
|
|
|
|
|
|
|
|
function api.broadcast (namespace_name, event, data)
|
2023-10-17 18:38:43 +00:00
|
|
|
if not namespaces[namespace_name] then return end
|
2023-10-17 17:19:35 +00:00
|
|
|
|
2023-10-17 18:38:43 +00:00
|
|
|
local listeners = api.namespace(namespace_name).listeners
|
|
|
|
if not listeners[event] then return end
|
|
|
|
|
|
|
|
for _, listener in pairs(listeners[event]) do
|
2023-10-17 17:19:35 +00:00
|
|
|
listener.callback(data, event)
|
|
|
|
end
|
|
|
|
end
|