Re: AW: AW: Size of a non numerical indexed table
[
Date Prev][Date Next][
Thread Prev][
Thread Next]
[
Date Index]
[
Thread Index]
- Subject: Re: AW: AW: Size of a non numerical indexed table
- From: Rici Lake <lua@...>
- Date: 2005年8月31日 17:41:21 -0500
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
or
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.