lua-users home
lua-l archive

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



On 21/11/14 01:58 PM, Luiz Henrique de Figueiredo wrote:
<SoniEx2> I wish Lua had a way to count keys in a table
This question often appears here and in
http://stackoverflow.com/questions/tagged/lua and it always strikes me:
why would you need to count entries in a table? It seems to me that
this is rarely required, and that it is probably an instance of
The XY Problem <http://xyproblem.info/> and trying to use in Lua using
paradigms from other languages. Perhaps I'm missing something.

This requests also springs from a misconception that Lua already
stores this value internally anyway, which it doesn't.

If you really need to count entries in a table you can use:

function number_of_entries(t)
	local n=0
	local k=nil
	while true do
		k=next(t,k)
		if k==nil then return n end
		n=n+1
	end
end

But there is really no need for an *operator* for that.

Well say you have 2 functions, one for heavy tables and another for light tables, and you wanna pick the right one for the right job. The current way is to use:

function nkeys(t)
  local c = 0
  for x in next, t do
    c = c + 1
  end
  return c
end

But if you're the Lua internals, you could instead do this:

*something somewhere calls rawset*
1. if key exists and value is nil, then decrement
2. else if key doesn't exist and value is not nil, then increment
*do normal rawset stuff*

*GC collection of weak keys/values*
*GC detects a weak key/value to destroy*
1. call rawset with key and nil
*GC does normal GC stuff*

Which would be much more efficient.