lua-users home
lua-l archive

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


Op 17 april 2012 17:17 heeft Coda Highland <chighland@gmail.com> het
volgende geschreven:
>> Maybe (I dunno) it would be good to also habe a table.len function,
>> which does a slow but reliable count for all types of tables, but of
>> course the # operator still has a valuable place.
>
> This was exactly what I was thinking, and it's a good idea. Have
> table.len() iterate over the full (internally-allocated) length of the
> array part of the table and... what, return the highest index? return
> the number of non-nil elements? Which would be better?
>
Why not both?

Since this thread seems intent on plodding through the well-trodden paths
yet again, I'd like to point out (not for the first time) that you don't need
to persuade LHF or Roberto to put these in Lua 5.3 or Lua 6.0.

Nothing and nobody stops you from doing this:

function table.count(tbl)
   local c=0
   for k in pairs(tbl) do c=c+1 end
   return c
end

function table.last(tbl)
   local c=nil
   for k in pairs(tbl) do if type(k)=='number' and k>=(c or k) then c=k end end
   return c
end

a={10,20,30,nil,-6,[400]=true}
print(table.count(a),table.last(a)) --> 5 400

In fact, that's what they want you to do.  Here is a quote from the 5.2 manual:

> Function table.maxn is deprecated. Write it in Lua if you really need it.