]> git.ipfire.org Git - thirdparty/rspamd.git/commitdiff
[Minor] Add `lua_util.nkeys` utility
authorVsevolod Stakhov <vsevolod@highsecure.ru>
Tue, 26 Nov 2019 19:23:58 +0000 (19:23 +0000)
committerVsevolod Stakhov <vsevolod@highsecure.ru>
Tue, 26 Nov 2019 19:23:58 +0000 (19:23 +0000)
lualib/lua_util.lua

index bda8b0c02c5fd4c2ff4c00db98e95cede8acaa4a..207bdc0dc923b603699fcde24b6a6616f6febeb2 100644 (file)
@@ -422,6 +422,30 @@ end
 
 exports.list_to_hash = list_to_hash
 
+--[[[
+-- @function lua_util.nkeys(table|gen, param, state)
+-- Returns number of keys in a table (i.e. from both the array and hash parts combined)
+-- @param {table} list numerically-indexed table or string, which is treated as a one-element list
+-- @return {number} number of keys
+-- @example
+-- print(lua_util.nkeys({}))  -- 0
+-- print(lua_util.nkeys({ "a", nil, "b" }))  -- 2
+-- print(lua_util.nkeys({ dog = 3, cat = 4, bird = nil }))  -- 2
+-- print(lua_util.nkeys({ "a", dog = 3, cat = 4 }))  -- 3
+--
+--]]
+local function nkeys(gen, param, state)
+  local n = 0
+  if not param then
+    for _,_ in pairs(gen) do n = n + 1 end
+  else
+    for _,_ in fun.iter(gen, param, state) do n = n + 1 end
+  end
+  return n
+end
+
+exports.nkeys = nkeys
+
 --[[[
 -- @function lua_util.parse_time_interval(str)
 -- Parses human readable time interval