Table.getsize does not factor in key names

table.getsize does not detect and count values when the key is a string

print(table.getsize({}))
-- arrayCount = 0, hashCount = 1

print(table.getsize({ mykey = "myvalue" }))
-- arrayCount = 0, hashCount = 1  /!\ /!\ /!\ /!\

print(table.getsize({ 1 }))
-- arrayCount = 1, hashCount = 1

Here is an implementation that returns the correct size:

function table.truesize(t)
    local count = 0
    for _, _ in pairs(t) do count += 1 end
    return count
end

I believe this is functioning as designed: the arrayCount counts table members that have integer indices (like arrays), though it's inaccurate if there are gaps (same as Lua's # operator). The count of members with string indices is returned in hashCount.

There seems to be a minimum value of 1 for hashCount, though, which might be a bug. We'll take a look at that. Thanks!

1 Like