aboutsummaryrefslogtreecommitdiffstats
path: root/util/events.lua
diff options
context:
space:
mode:
Diffstat (limited to 'util/events.lua')
-rw-r--r--util/events.lua39
1 files changed, 21 insertions, 18 deletions
diff --git a/util/events.lua b/util/events.lua
index b1f3811c..3816f30b 100644
--- a/util/events.lua
+++ b/util/events.lua
@@ -2,6 +2,7 @@
local ipairs = ipairs;
local pairs = pairs;
local t_insert = table.insert;
+local t_sort = table.sort;
local select = select;
module "events"
@@ -10,32 +11,32 @@ function new()
local dispatchers = {};
local handlers = {};
local event_map = {};
- local function _rebuild_index() -- TODO optimize index rebuilding
- for event, _handlers in pairs(event_map) do
- local index = handlers[event];
- if index then
- for i=#index,1,-1 do index[i] = nil; end
- else index = {}; handlers[event] = index; end
- for handler in pairs(_handlers) do
- t_insert(index, handler);
- end
+ local function _rebuild_index(event) -- TODO optimize index rebuilding
+ local _handlers = event_map[event];
+ local index = handlers[event];
+ if index then
+ for i=#index,1,-1 do index[i] = nil; end
+ else index = {}; handlers[event] = index; end
+ for handler in pairs(_handlers) do
+ t_insert(index, handler);
end
+ t_sort(index, function(a, b) return _handlers[a] > _handlers[b]; end);
end;
- local function add_handler(event, handler)
+ local function add_handler(event, handler, priority)
local map = event_map[event];
if map then
- map[handler] = true;
+ map[handler] = priority or 0;
else
- map = {[handler] = true};
+ map = {[handler] = priority or 0};
event_map[event] = map;
end
- _rebuild_index();
+ _rebuild_index(event);
end;
local function remove_handler(event, handler)
local map = event_map[event];
if map then
map[handler] = nil;
- _rebuild_index();
+ _rebuild_index(event);
end
end;
local function add_plugin(plugin)
@@ -51,9 +52,10 @@ function new()
local function _create_dispatcher(event) -- FIXME duplicate code in fire_event
local h = handlers[event];
if not h then h = {}; handlers[event] = h; end
- local dispatcher = function(data)
+ local dispatcher = function(...)
for _, handler in ipairs(h) do
- handler(data);
+ local ret = handler(...);
+ if ret ~= nil then return ret; end
end
end;
dispatchers[event] = dispatcher;
@@ -62,11 +64,12 @@ function new()
local function get_dispatcher(event)
return dispatchers[event] or _create_dispatcher(event);
end;
- local function fire_event(event, data) -- FIXME duplicates dispatcher code
+ local function fire_event(event, ...) -- FIXME duplicates dispatcher code
local h = handlers[event];
if h then
for _, handler in ipairs(h) do
- handler(data);
+ local ret = handler(...);
+ if ret ~= nil then return ret; end
end
end
end;