lua-users home
lua-l archive

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

2010/1/15 Roberto Ierusalimschy <>:
>> Agreed. The only reason #t has its undefined behavior is because it is
>> impractical for it to iterate the table.
> I disagree. In my point of view, there is no sensible semantics for #t
> when the table has holes.
> Consider the "lists" below and think what should be their length:
>  {1, 1, nil, 1, 1, 1, 1, 1, 1, 1, 1}
>  {1, 1, nil, 1}
>  {1, 1, nil, 1, nil}
>  {nil, nil, nil}
>  {[100000] = 1}

>From a programmer point of view, #t defined as max(k) for k>=1 and
t[k]~=nil (or 0 if no such k exists) makes the most sense to me. This
definition is unambiguous, doesn't depend on the pattern of
insertions/deletions to/from a table and is what you normally want to
know (i.e. how big is the continuous block of array elements you can
iterate on). Sparse arrays (arrays with holes) need to be handled with
pairs anyway in order to catch all the keys.

The main reason for me to use ipairs was that it behaved as max(k)
above. If ipairs will now respect #t,
 it seems redundant to have it. I expect the following pattern will
become quite common in Lua 5.2 (especially in a library type code,
which needs to work for generic input):

for k,v in ipairs(t) do
  if v==nil
  -- loop body here