aboutsummaryrefslogtreecommitdiffstats
path: root/util
diff options
context:
space:
mode:
authorMatthew Wild <mwild1@gmail.com>2009-04-22 18:00:45 +0100
committerMatthew Wild <mwild1@gmail.com>2009-04-22 18:00:45 +0100
commit34a4b98cf6dbb4a97dda590d16832ffcd196bd3a (patch)
tree974744c9d763d22f51f30b2f00a25078aa4e929f /util
parent1ce9466289eaa1843e503b951078fc4432ce96c4 (diff)
downloadprosody-34a4b98cf6dbb4a97dda590d16832ffcd196bd3a.tar.gz
prosody-34a4b98cf6dbb4a97dda590d16832ffcd196bd3a.zip
util.set: Add metatable to sets to allow +, -, /, ==, tostring and to double as iterators
Diffstat (limited to 'util')
-rw-r--r--util/set.lua58
1 files changed, 54 insertions, 4 deletions
diff --git a/util/set.lua b/util/set.lua
index f550a721..892f1c9d 100644
--- a/util/set.lua
+++ b/util/set.lua
@@ -1,10 +1,60 @@
-local ipairs, pairs =
- ipairs, pairs;
+local ipairs, pairs, setmetatable, next, tostring =
+ ipairs, pairs, setmetatable, next, tostring;
+local t_concat = table.concat;
module "set"
+local set_mt = {};
+function set_mt.__call(set, _, k)
+ return next(set._items, k);
+end
+function set_mt.__add(set1, set2)
+ return _M.union(set1, set2);
+end
+function set_mt.__sub(set1, set2)
+ return _M.difference(set1, set2);
+end
+function set_mt.__div(set, func)
+ local new_set, new_items = _M.new();
+ local items, new_items = set._items, new_set._items;
+ for item in pairs(items) do
+ if func(item) then
+ new_items[item] = true;
+ end
+ end
+ return new_set;
+end
+function set_mt.__eq(set1, set2)
+ local set1, set2 = set1._items, set2._items;
+ for item in pairs(set1) do
+ if not set2[item] then
+ return false;
+ end
+ end
+
+ for item in pairs(set2) do
+ if not set1[item] then
+ return false;
+ end
+ end
+
+ return true;
+end
+function set_mt.__tostring(set)
+ local s, items = { }, set._items;
+ for item in pairs(items) do
+ s[#s+1] = tostring(item);
+ end
+ return t_concat(s, ", ");
+end
+
+local items_mt = {};
+function items_mt.__call(items, _, k)
+ return next(items, k);
+end
+
function new(list)
- local items = {};
+ local items = setmetatable({}, items_mt);
local set = { _items = items };
function set:add(item)
@@ -45,7 +95,7 @@ function new(list)
set:add_list(list);
end
- return set;
+ return setmetatable(set, set_mt);
end
function union(set1, set2)