lua-users home
lua-l archive

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


This is kind of an interesting point, actually. Does anyone know the rationale for not just automatically tracking the number of entries in a table? Similar data structures in many other languages do this. I know that's not in an of itself a reason to do anything, but it does seem useful. If you know you're dealing with a sequence a sequence, then #t effectively becomes constant instead of logarithmic. And if you don't know it's a sequence (or you know it's not) then you have a convenient counting method that doesn't involve an iterator.

Is it just the (perceived or actual) runtime overhead?

On Sat, May 30, 2015 at 8:55 PM, Coda Highland <chighland@gmail.com> wrote:
On Sat, May 30, 2015 at 8:16 PM, Soni L. <fakedme@gmail.com> wrote:
> In Lua 5.1 table.maxn is linear, #t is not. table.maxn only gives sequences,
> #t may or may not give sequences...
> If table.maxn != #t... why did table.maxn get removed again?
>
> (At least the Lua 5.1 reference manual says table.maxn is linear...)

#t is not linear because it's better than linear -- it's logarithmic.
Furthermore, #t and table.maxn will always agree in the case that the
table is a sequence.

In practice, using maxn is almost always a mistake. It has inferior
performance (and the bigger your table is, the worse the gap gets) and
any design where you care about the difference between a sequence and
a non-sequence and you don't know in advance which you're looking at
is dubious at best. Seriously, if you're dealing in sequences, then
you ought to know you're dealing in sequences, at which point you
should be using #t for the performance. And if you're dealing in
arbitrary tables that may or may not be a sequence, you shouldn't be
trying to treat them as sequences at all, but rather explicitly
tracking a length or something.

/s/ Adam




--
Brigham Toskin