lua-users home
lua-l archive

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



On 20-Mar-05, at 5:25 PM, Eric Tetz wrote:
How can I tell the number of elements in table T? I'm not using it as
a list, so table.getn always returns 0. Do I need to write something
like this?

function numelements (t)
  local n = 0
  for k,v in t do
    n = n + 1
  end
  return n
end

Exactly.

That seems very kludgey.

Perhaps. But why would you want to know?

The closest I usually come to this question is asking whether a table is empty, or sometimes if it has more than one key/value pair. The following are useful:

function is_empty(t) return next(t) == nil end

function is_multiple(t)
  local first = next(t)
  return next(t, first) ~= nil
end

and for what its worth

function has_at_least(t, n)
  local k = nil
  for i = 1, n do
    k = next(t, k)
    if k == nil then return false end
  end
  return true
end