Merge pull request #3294 from sclu1034/feature/count_keys

Add utility to count table keys
This commit is contained in:
mergify[bot] 2021-04-01 07:42:25 +00:00 committed by GitHub
commit 7a8fa9d27a
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 53 additions and 0 deletions

View File

@ -165,6 +165,23 @@ 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)`.
--
-- @DOC_text_gears_table_count_keys_EXAMPLE@
--
-- @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.

View File

@ -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 })
@ -104,3 +132,5 @@ describe("gears.table", function()
end)
end)
end)
-- vim: filetype=lua:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:textwidth=80

View File

@ -0,0 +1,6 @@
--DOC_GEN_OUTPUT --DOC_HIDE
local gears = require("gears") --DOC_HIDE
local tab = { 1, nil, "a", "b", foo = "bar" }
local count = gears.table.count_keys(tab)
print("The table has " .. count .. " keys")