[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: Bug report in length of simple table
- From: Duncan Cross <duncan.cross@...>
- Date: Tue, 13 Sep 2016 13:26:42 +0100
On Tue, Sep 13, 2016 at 9:35 AM, <Tomas.Lavicka@tieto.com> wrote:
> Program:
>
> Lua 5.3.3 Copyright (C) 1994-2016 Lua.org, PUC-Rio
>
> > a={}
>
> > a[1]=1
>
> > a[2]=nil
>
> > a[3]=3
>
> > a[4]=4
>
> > print(#a)
>
> 4
>
> should returns value 1 but because a[2] is nil, it should return value 1
> according book “Programming in Lua (Third edition)” – there is hole in
> sequence.
>
>
>
> Tomas Lavicka
>
> Ostrava, Czech Republic
Here's how you should think of it: #a will return ANY non-negative
integer n, where a[n] is not nil and a[n+1] is nil, OR if a[1] is nil,
#a MAY also return 0.
So if there are holes, then that means there are multiple,
equally-valid values for #a, and it should be considered completely
arbitrary which one you will get. (Even if it appears consistent, in
your own experiments.)
It is essentially your responsibility to make sure there is only one
valid value for n, in order to maintain a coherent "length" for a
particular table.
(All of this is only talking about default behavior, ignoring tables
that have the __len metamethod defined.)
-Duncan