Software /
code /
prosody
Comparison
util/filters.lua @ 3133:d3f16b4c1ecb
util.filters: New utility library for managing filters on an object
author | Matthew Wild <mwild1@gmail.com> |
---|---|
date | Wed, 02 Jun 2010 12:20:29 +0100 |
child | 3134:9a29ad6a9b97 |
comparison
equal
deleted
inserted
replaced
3132:4d2251242ac1 | 3133:d3f16b4c1ecb |
---|---|
1 -- Prosody IM | |
2 -- Copyright (C) 2008-2010 Matthew Wild | |
3 -- Copyright (C) 2008-2010 Waqas Hussain | |
4 -- | |
5 -- This project is MIT/X11 licensed. Please see the | |
6 -- COPYING file in the source package for more information. | |
7 -- | |
8 | |
9 local t_insert, t_remove = table.insert, table.remove; | |
10 | |
11 module "filters" | |
12 | |
13 local function initialize_session(session) | |
14 local filters = {}; | |
15 session.filters = filters; | |
16 | |
17 function session.filter(type, data) | |
18 local filter_list = filters[type]; | |
19 for i = 1, #filter_list do | |
20 data = filter_list[i](data); | |
21 end | |
22 return data; | |
23 end | |
24 end | |
25 | |
26 function add_filter(session, type, callback, priority) | |
27 if not session.filters then | |
28 initialize_session(session); | |
29 end | |
30 | |
31 local filter_list = session.filters[type]; | |
32 if not filter_list then | |
33 filter_list = {}; | |
34 session.filters[type] = filter_list; | |
35 end | |
36 | |
37 priority = priority or 0; | |
38 | |
39 local i = 0; | |
40 repeat | |
41 i = i + 1; | |
42 until not filter_list[i] or filter_list[filter_list[i]] >= priority; | |
43 | |
44 t_insert(filter_list, i, callback); | |
45 filter_list[callback] = priority; | |
46 end | |
47 | |
48 function remove_filter(session, type, callback) | |
49 local filter_list = session.filters[type]; | |
50 if filter_list and filter_list[callback] then | |
51 for i=1, #filter_list do | |
52 if filter_list[i] == callback then | |
53 t_remove(filter_list, i); | |
54 filter_list[callback] = nil; | |
55 return true; | |
56 end | |
57 end | |
58 end | |
59 end | |
60 | |
61 return _M; |