Add utility to count table keys

See #3293.

Signed-off-by: Lucas Schwiderski <lucas@lschwiderski.de>
This commit is contained in:
Lucas Schwiderski 2021-03-22 20:21:15 +01:00
parent dab84c2662
commit 07df24f7d0
No known key found for this signature in database
GPG Key ID: AA12679AAA6DF4D8
2 changed files with 43 additions and 0 deletions

View File

@ -165,6 +165,21 @@ function gtable.keys(t)
return keys return keys
end end
--- Get the number of keys in a table, both integer and string indicies.
--
-- This is functionally equivalent, but faster than `#gears.table.keys(t)`.
--
-- @tparam table t The table for which to count the keys.
-- @treturn number The number of keys in the table.
-- @staticfct gears.table.count_keys
function gtable.count_keys(t)
local count = 0
for _, _ in pairs(t) do
count = count + 1
end
return count
end
--- Filter a table's keys for certain content type. --- Filter a table's keys for certain content type.
-- --
-- @tparam table t The table to retrieve the keys for. -- @tparam table t The table to retrieve the keys for.

View File

@ -7,6 +7,34 @@ describe("gears.table", function()
assert.is.same(gtable.keys(t), { 1, 2, "a" }) assert.is.same(gtable.keys(t), { 1, 2, "a" })
end) end)
describe("gears.table.count_keys", function()
it("counts keys in an empty table", function()
local t = {}
assert.is.same(gtable.count_keys(t), 0)
end)
it("counts keys in a sparse array", function()
local t = { 1, nil, 3 }
assert.is.same(gtable.count_keys(t), 2)
end)
it("counts keys in a regular array", function()
local t = { 1, 2, 3 }
assert.is.same(gtable.count_keys(t), 3)
end)
it("counts keys in a hash table", function()
local t = { a = 1, b = "2", c = true }
assert.is.same(gtable.count_keys(t), 3)
end)
it("counts keys in a mixed table", function()
local t = { 1, a = 2, nil, 4 }
assert.is.same(gtable.count_keys(t), 3)
end)
end)
it("table.keys_filter", function() it("table.keys_filter", function()
local t = { "a", 1, function() end, false} local t = { "a", 1, function() end, false}
assert.is.same(gtable.keys_filter(t, "number", "function"), { 2, 3 }) assert.is.same(gtable.keys_filter(t, "number", "function"), { 2, 3 })