Small fix for multitable
[prosody.git] / util / multitable.lua
1 -- Prosody IM v0.1
2 -- Copyright (C) 2008 Matthew Wild
3 -- Copyright (C) 2008 Waqas Hussain
4 -- 
5 -- This program is free software; you can redistribute it and/or
6 -- modify it under the terms of the GNU General Public License
7 -- as published by the Free Software Foundation; either version 2
8 -- of the License, or (at your option) any later version.
9 -- 
10 -- This program is distributed in the hope that it will be useful,
11 -- but WITHOUT ANY WARRANTY; without even the implied warranty of
12 -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 -- GNU General Public License for more details.
14 -- 
15 -- You should have received a copy of the GNU General Public License
16 -- along with this program; if not, write to the Free Software
17 -- Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
18 --
19
20
21
22 local select = select;
23 local t_insert = table.insert;
24 local pairs = pairs;
25 local next = next;
26
27 module "multitable"
28
29 local function get(self, ...)
30         local t = self.data;
31         for n = 1,select('#', ...) do
32                 t = t[select(n, ...)];
33                 if not t then break; end
34         end
35         return t;
36 end
37
38 local function add(self, ...)
39         local t = self.data;
40         local count = select('#', ...);
41         for n = 1,count-1 do
42                 local key = select(n, ...);
43                 local tab = t[key];
44                 if not tab then tab = {}; t[key] = tab; end
45                 t = tab;
46         end
47         t_insert(t, (select(count, ...)));
48 end
49
50 local function r(t, n, _end, ...)
51         if t == nil then return; end
52         if n > _end then
53                 for key in pairs(t) do
54                         t[key] = nil;
55                 end
56         end
57         local k = select(n, ...);
58         if k then
59                 v = t[k];
60                 if v then
61                         r(v, n+1, _end, ...);
62                         if not next(v) then
63                                 t[k] = nil;
64                         end
65                 end
66         else
67                 for _,b in pairs(t) do
68                         r(b, n+1, _end, ...);
69                         if not next(b) then
70                                 t[_] = nil;
71                         end
72                 end
73         end
74 end
75
76 local function remove(self, ...)
77         local _end = select('#', ...);
78         for n = _end,1 do
79                 if select(n, ...) then _end = n; break; end
80         end
81         r(self.data, 1, _end, ...);
82 end
83
84
85 function new()
86         return {
87                 data = {};
88                 get = get;
89                 add = add;
90                 remove = remove;
91         };
92 end
93
94 return _M;