If you have control of the construction of the table, you can keep a count yourself the whole time
using techniques like this:
http://www.lua.org/pil/13.4.4.html
That example tracks all accesses, but you could easily modify it to only track non-integer inserts.
Adam D. Moss wrote:
Matt Campbell wrote:
The only way I know to count non-indexed values in a table is like this:
function countFields(t)
local count = 0
for k, v in pairs(t) do
count = count + 1
end
return count
end
Does anyone have a better solution?
The above will count all values, not just non-integer-index
parts of the table. The length operator will also not be
useful where the integer-index parts of the table are
sparse.
I guess something like this is what's wanted:
function countFields(t)
local count = 0
for k, v in pairs(t) do
count = count + 1
end
for k, v in ipairs(t) do
count = count - 1
end
return count
end
(brr!!!)
--adam