lua-users home
lua-l archive

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

On 31-Aug-05, at 4:39 PM, steffenj wrote:

i'm just used to using foreach(i) and never use (i)pairs
but if iterating over the table can be avoided by using a metatable (not
sure if it's possible but i guess so), i would go for the metatable
solution, especially if "TableSize" were a function that is called often or
if the tables were quite large

I have never actually run into a use case for counting keys in a table, other than wanting to know if the table was empty or not (or occasionally if the table has more than one key in it). So I think that Wim's suggestion is just fine for most cases:

if next(t) then -- table is not empty -- end


if next(t, next(t)) then -- table has at least one key -- end

will cover most of the useful cases.

If you really for some reason need to know how many keys there are, it would almost always be better to count them when needed than to try to maintain the count interactively. The only exception would be the ultra-rare case when you were constantly calling tablesize(), in which case you'd be best off re-examining your algorithm.

The metatable solution wouldn't work because it doesn't let you track deletions. But repeated deletions are precisely why it's generally better to count on demand than to try to maintain a count; it avoids extra work.