Add utility to count table keys
See #3293. Signed-off-by: Lucas Schwiderski <lucas@lschwiderski.de>
This commit is contained in:
parent
dab84c2662
commit
07df24f7d0
|
@ -165,6 +165,21 @@ function gtable.keys(t)
|
|||
return keys
|
||||
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.
|
||||
--
|
||||
-- @tparam table t The table to retrieve the keys for.
|
||||
|
|
|
@ -7,6 +7,34 @@ describe("gears.table", function()
|
|||
assert.is.same(gtable.keys(t), { 1, 2, "a" })
|
||||
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()
|
||||
local t = { "a", 1, function() end, false}
|
||||
assert.is.same(gtable.keys_filter(t, "number", "function"), { 2, 3 })
|
||||
|
|
Loading…
Reference in New Issue