lua-users home
lua-l archive

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


> <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.