lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


I'm not exactly new to this list, but i'm also definitively not a lua expert. I know things like this have been discussed before, but:

why does lua not keep track of its table sizes?

Is it a performance issue? Overhead of actually counting inserts and deletes? Or are there other issues?

Because I find myself more than once going through tables, counting elements to find the table size.

// David Morris-Oliveros
// Camera & Lua Coder
// david@teambondi.com



Tyranni wrote:
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