lua-users home
lua-l archive

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


Andrea:

On Thu, May 21, 2020 at 5:53 PM Andrea <andrea.l.vitali@gmail.com> wrote:
> why ipairs does exist when one can do a for loop from 1 to #t?

IIRC correctly ipairs stop at the first nil, which may be before #t (
I think #t guarantees it is 0 or t[#t] is not nil and t[#t+1] is nil,
it does not
say anything about the keys before:

Lua 5.3.3  Copyright (C) 1994-2016 Lua.org, PUC-Rio
> t={1,2,3,4,5,6,7,8,9}
> t[3]=nl
> for i=1,#t do print(i,t[i]) end
1    1
2    2
3    nil
4    4
5    5
6    6
7    7
8    8
9    9
> for i,v in ipairs(t) do print(i,v) end
1    1
2    2
>

( they are the same for what people call "sequences", tables without "holes" ).

an equivalent loop to ipairs ignoring overflows, would be something like
    "for i=1,matx.maxinteger do local v=t[i] if v==nil break end ....end"
, ignoring some gory details.

Francisco Olarte.