diff --git a/lib/gears/table.lua b/lib/gears/table.lua index 118971c20..6572fdd3a 100644 --- a/lib/gears/table.lua +++ b/lib/gears/table.lua @@ -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. diff --git a/spec/gears/table_spec.lua b/spec/gears/table_spec.lua index dbe836a88..1c33055d4 100644 --- a/spec/gears/table_spec.lua +++ b/spec/gears/table_spec.lua @@ -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 })