lua-users home
lua-l archive

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


On Tue, Oct 03, 2006 at 12:12:38PM -0700, Sam Roberts wrote:
> > >I am just wondering if there's a good way of finding whether a  
> > >given Lua
> > >table is actually an array.
> > 
> > >One way is to iterate over the table using 'pairs' and see if any  
> > >of the
> > >keys is a non-number.
> 
> If you mean array as in the definition used by the # operator
> 
>   For a regular array, with non-nil values from 1 to a given n, its
>   length is exactly that n

Rather,

   The length of a table t is defined to be any integer index n such
   that t[n] is not nil and t[n+1] is nil

Note that an array can have holes; they're even mentioned further down
in 2.5.5.

> And you want to make sure the table meets those conditions (why? :-),
> then doing pairs() and checking each key is >=1 and <= #t, and that you
> see exactly #t of them, should work. I don't think that pairs() will
> return a key if the value is nil.

... and integral.

(I also have some difficulty thinking of a real use for wanting to know
this; if someone gives an example, it may be easier to know exactly what's
wanted.)

-- 
Glenn Maynard