lua-users home
lua-l archive

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

On Saturday, May 30, 2015, Brigham Toskin <> wrote:
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 <> wrote:
On Sat, May 30, 2015 at 8:16 PM, Soni L. <> 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

I believe that it would be complicated to write a generally efficient maxn method.  

Sometimes tracking `n` is good? I do that when packing arguments into a table because some arguments are nil. 

I have a keyframe object that needs to be ordered by a the time value, which is not a sequence:

`{{0, [value]}, {100, [value]}}`

This works better for me. When I am treating this as a timeline/sequence, `#` evaluates to 100. As a keyframe list, it's 2. 

A general `maxn` may have guided me to a different solution, but I don't think it would have been better. It's presence would have somewhat obliged me to use it, if I wanted it to be more accessible to Lua programmers. It's absence caused me to think about the problem more deeply and I think the result is better. 

- Andrew

I apologize for adding to the volume of "Lua / array (part) / sequence / length" material. I thought it worth pointing out that features can have the unintended... soft consequences.