summaryrefslogtreecommitdiffstats
path: root/lualib/lua_util.lua
diff options
context:
space:
mode:
authorVsevolod Stakhov <vsevolod@highsecure.ru>2017-10-15 12:42:56 +0100
committerVsevolod Stakhov <vsevolod@highsecure.ru>2017-10-15 12:42:56 +0100
commitf28e506d40991c122d5511e2979feb844be22009 (patch)
treef4815d48b8f5ef0e6852a9d6ea1c352946edcd77 /lualib/lua_util.lua
parent8a16c2c819b2a4513ad2f7e3cf675eb91737bad6 (diff)
downloadrspamd-f28e506d40991c122d5511e2979feb844be22009.tar.gz
rspamd-f28e506d40991c122d5511e2979feb844be22009.zip
[Minor] Add spairs function to lua lib
Diffstat (limited to 'lualib/lua_util.lua')
-rw-r--r--lualib/lua_util.lua34
1 files changed, 34 insertions, 0 deletions
diff --git a/lualib/lua_util.lua b/lualib/lua_util.lua
index f048432bf..a160bd85e 100644
--- a/lualib/lua_util.lua
+++ b/lualib/lua_util.lua
@@ -165,4 +165,38 @@ exports.unpack = function(t)
return unpack_function(t)
end
+-- Sorted iteration:
+-- for k,v in spairs(t) do ... end
+--
+-- or with custom comparison:
+-- for k, v in spairs(t, function(t, a, b) return t[a] < t[b] end)
+--
+-- optional limit is also available (e.g. return top X elements)
+local function spairs(t, order, lim)
+ -- collect the keys
+ local keys = {}
+ for k in pairs(t) do keys[#keys+1] = k end
+
+ -- if order function given, sort by it by passing the table and keys a, b,
+ -- otherwise just sort the keys
+ if order then
+ table.sort(keys, function(a,b) return order(t, a, b) end)
+ else
+ table.sort(keys)
+ end
+
+ -- return the iterator function
+ local i = 0
+ return function()
+ i = i + 1
+ if not lim or i <= lim then
+ if keys[i] then
+ return keys[i], t[keys[i]]
+ end
+ end
+ end
+end
+
+exports.spairs = spairs
+
return exports