Table elements with non-numerical keys won't count towards the length of the table when using either the # operator or the table.getn function.
A solution to this, although not very convenient, is to keep track of the length of the table manually:
local myTable = {
length = 0
}
myTable["key"] = "value"
myTable.length = myTable.length + 1
print(myTable.length)
Alternatively, you could use a metatable to do it for you, but that will require an empty table to serve as a proxy:
local myTableProxy = {
length = 0
}
do
local actualTable = {}
setmetatable(myTableProxy, {
__index = actualTable,
__newindex = function(t, k, v)
local oldValue = t[k]
local newLength = t.length or 0
if oldValue == nil and v ~= nil then
newLength = newLength + 1
elseif oldValue ~= nil and v == nil then
newLength = newLength - 1
end
rawset(t, "length", newLength)
rawset(actualTable, k, v)
end
})
end
myTableProxy["key"] = "value"
print(myTableProxy.length)
but I won't explain this technique any further, as it is out of the scope of this answer. This solution also makes it impossible for actualTable to contain an element with key named "length".
2 comments
Actually, this only happens with dictionaries.
Ah, may have gotten a few of my terms mixed up. A bit tired.