Suspicious table initialization

Previous Topic Next Topic
 
classic Classic list List threaded Threaded
4 messages Options
Reply | Threaded
Open this post in threaded view
|

Suspicious table initialization

Grzegorz Krasoń
How to understand the difference between t1 and t2 in the example below? They give the same results while iterating, but `#` returns different values. Is this expected?

```lua
> t1 = {[3] = 100}
> t2 = {nil, nil, 100}
> for x, y in pairs(t1) do print(x, y) end
3       100
> for x, y in pairs(t2) do print(x, y) end
3       100
> #t1
0
> #t2
3
```
Reply | Threaded
Open this post in threaded view
|

Re: Suspicious table initialization

Matthew Wild
On Tue, 27 Oct 2020, 19:27 Grzegorz Krasoń, <[hidden email]> wrote:
How to understand the difference between t1 and t2 in the example below? They give the same results while iterating, but `#` returns different values. Is this expected?

Yes, it is expected. See the definition of the length operator in the manual: https://www.lua.org/manual/5.4/manual.html#3.4.7

Specifically, your example tables are not sequences and the length operator may return one of multiple possible values for such a table.

Regards,
Matthew
Reply | Threaded
Open this post in threaded view
|

Re: Suspicious table initialization

Javier Guerra Giraldez
In reply to this post by Grzegorz Krasoń
On Tue, 27 Oct 2020 at 14:27, Grzegorz Krasoń <[hidden email]> wrote:
>
> How to understand the difference between t1 and t2 in the example below? They give the same results while iterating, but `#` returns different values.
> Is this expected?

yes

> > t1 = {[3] = 100}
> > t2 = {nil, nil, 100}

these are two different tables with equal contents.  the difference is
that they are independent objects.

the `#` operator returns a number such that t[#t+1] == nil and either
#t == 0 or t[#t] ~= nil.

in both t1 and t2 it would be valid to return either 0 or 3.  which
one is undefined.


--
Javier
Reply | Threaded
Open this post in threaded view
|

Re: Suspicious table initialization

Grzegorz Krasoń
Thank you for the answers and references. It is clear now!

On Tue, 27 Oct 2020 at 20:53, Javier Guerra Giraldez <[hidden email]> wrote:
On Tue, 27 Oct 2020 at 14:27, Grzegorz Krasoń <[hidden email]> wrote:
>
> How to understand the difference between t1 and t2 in the example below? They give the same results while iterating, but `#` returns different values.
> Is this expected?

yes

> > t1 = {[3] = 100}
> > t2 = {nil, nil, 100}

these are two different tables with equal contents.  the difference is
that they are independent objects.

the `#` operator returns a number such that t[#t+1] == nil and either
#t == 0 or t[#t] ~= nil.

in both t1 and t2 it would be valid to return either 0 or 3.  which
one is undefined.


--
Javier