X-Git-Url: https://git.enpas.org/?a=blobdiff_plain;f=util%2Fmultitable.lua;h=dbf34d28ff33e4ba8c453270f2b751eeda128066;hb=45bd459efc454df5e34674dbc7086402b71a973d;hp=397f9ebeb77a3660a3fd5be6025169cdadcfa5b0;hpb=1ac6f4f447789e730146fe99ddfe1bd6c7e0556b;p=prosody.git diff --git a/util/multitable.lua b/util/multitable.lua index 397f9ebe..dbf34d28 100644 --- a/util/multitable.lua +++ b/util/multitable.lua @@ -1,17 +1,14 @@ --- Prosody IM v0.3 --- Copyright (C) 2008-2009 Matthew Wild --- Copyright (C) 2008-2009 Waqas Hussain +-- Prosody IM +-- Copyright (C) 2008-2010 Matthew Wild +-- Copyright (C) 2008-2010 Waqas Hussain -- -- This project is MIT/X11 licensed. Please see the -- COPYING file in the source package for more information. -- - - local select = select; local t_insert = table.insert; -local pairs = pairs; -local next = next; +local unpack, pairs, next, type = unpack, pairs, next, type; module "multitable" @@ -56,7 +53,7 @@ local function r(t, n, _end, ...) return; end if k then - v = t[k]; + local v = t[k]; if v then r(v, n+1, _end, ...); if not next(v) then @@ -96,7 +93,7 @@ local function s(t, n, results, _end, ...) return; end if k then - v = t[k]; + local v = t[k]; if v then s(v, n+1, results, _end, ...); end @@ -129,6 +126,41 @@ local function search_add(self, results, ...) return results; end +function iter(self, ...) + local query = { ... }; + local maxdepth = select("#", ...); + local stack = { self.data }; + local keys = { }; + local function it(self) + local depth = #stack; + local key = next(stack[depth], keys[depth]); + if key == nil then -- Go up the stack + stack[depth], keys[depth] = nil, nil; + if depth > 1 then + return it(self); + end + return; -- The end + else + keys[depth] = key; + end + local value = stack[depth][key]; + if query[depth] == nil or key == query[depth] then + if depth == maxdepth then -- Result + local result = {}; -- Collect keys forming path to result + for i = 1, depth do + result[i] = keys[i]; + end + result[depth+1] = value; + return unpack(result, 1, depth+1); + elseif type(value) == "table" then + t_insert(stack, value); -- Descend + end + end + return it(self); + end; + return it, self; +end + function new() return { data = {}; @@ -138,6 +170,7 @@ function new() remove = remove; search = search; search_add = search_add; + iter = iter; }; end