lua-users home
lua-l archive

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


On Thu, May 21, 2020 at 3:39 PM Francisco Olarte <folarte@peoplecall.com> wrote:
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
>

And here's another argument for __ipairs: Imagine you want to write a array or list data structure that can include nils and is expected to iterate over the full length of the structure, including nils.

With __ipairs, it's easy to get it to work with the built-in ipairs(), making it much easier for people to use your library.

Without __ipairs, it's impossible to make it work with the built-in ipairs() since it forcibly stops as soon as __index returns nil, which forces you to write a custom :iter() method and educate users to use that instead (even though ipairs() is more natural to them), or worse, monkey-patch ipairs() to call the metamethod (and monkey-patching the standard library is a Bad Idea®).