lua-users home
lua-l archive

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


As you know, a table containing a sequence is still a table -- there is no `sequenced table` type.
Earlier, there was the question that `t.foo = 2` on a table with a sequence will produce an error, which it will not, as it is a table.

If something is surprising, it means something. In this case, that would be that the # operator has a gotcha attached to it.

- Advert

On Sat, Jan 20, 2018 at 2:41 AM, Coda Highland <chighland@gmail.com> wrote:
On Fri, Jan 19, 2018 at 8:15 PM, Advert Slaxxor <adv3r7@gmail.com> wrote:
> A table is a table. There is no such thing as a sequenced table. If you
> have:
>
> t = {1, 2, 3, 4}
> print(#t) -- 4
> t.foo = 2
> print(#t) -- 4
> print(t[4]) -- 4
> print(t.foo) -- 2
> -- continuing for below:
> t[5] = 5
> t[7] = 7
> print(#t) -- 5
> t[6] = 6
> print(#t) -- 7
> t[6] = nil
> print(#t) -- 5
>
> for i = 8, 2000 do
>  t[i] = i
> end
> print(#t) -- !! 2000
>
> As demonstrated, #t is not reliable if your table has the potential to hold
> nil (PiL mentions this, IIRC). I just ran this on the Lua site's demo, with
> _VERSION being 5.3
>
> - Advert

No, there very much exists the idea of a table that contains a
sequence. It's well-documented.

The fact that your example shows a surprising case means nothing.
Sequences are defined by the documentation to not contain nil. If your
table contains integer-valued keys with nil values, then your table is
not a sequence, which means the # operator does not have well-defined
behavior and the table module may or may not do the things you expect
it to do.

/s/ Adam