lua-users home
lua-l archive

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


This subject is too important to be buried in the big thread.

The idiom

   for k,v in ipairs(tbl) do

appears in numerous programs, very few of which are paranoid
enough to test (redundantly, up to now) that v is not nil. f you
explicitly supply __ipairs, you take responsibility, fair enough.

Now __ipairs is deprecated (although still recognized with default
compatibility options) and that idiom is equivalent to

   for k=1,#ipairs(tbl) do local v=tbl[k]

I can see the point when __len has been supplied. But __len is
a curious metamethod. It is not invoked, like most of the others,
when Lua does not know what to do. It is invoked in preference
to what Lua knows to do. Lua's default length operationis a  fallback
to a fallback. Its operation when a table has holes is one of the
most-hated features of Lua, to the extent that it is officially undefined.

Now "ipairs" used to be reliable even when the length operator
was undefined. This comfort, according to the 5.3.0-alpha manual,
is now taken away.

I made a little experiment. The present behaviour is that if you
do not override __len, ipairs still chickens out a soon as a nil
value is encountered. It does not do what the manual says.

I think this is the way it should be. The manual should be corrected.

$ lua53
Lua 5.3.0 (alpha)  Copyright (C) 1994-2014 Lua.org, PUC-Rio
> a={1,2,3,4,5,6,7,8,9,10}
> a[3]=nil
> #a
10
> for k in ipairs(a) do print(k) end
1
2
>