lua-users home
lua-l archive

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


Matt Campbell wrote:
The only way I know to count non-indexed values in a table is like this:

function countFields(t)
 local count = 0
 for k, v in pairs(t) do
   count = count + 1
 end
 return count
end

Does anyone have a better solution?

The above will count all values, not just non-integer-index
parts of the table.  The length operator will also not be
useful where the integer-index parts of the table are
sparse.

I guess something like this is what's wanted:

> function countFields(t)
>  local count = 0
>  for k, v in pairs(t) do
>    count = count + 1
>  end
>  for k, v in ipairs(t) do
>    count = count - 1
>  end
>  return count
> end

(brr!!!)

--adam