lua-users home
lua-l archive

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


On Tue, May 08, 2007 at 07:16:41AM -0300, Luiz Henrique de Figueiredo wrote:
> > It seems like there is no quick way to determine the number key-value
> > pairs in an associative table (short of iterating through and counting
> > them all).  If I am not missing something, why is there no quick way
> > to determine the number of key-value pairs in an associative table?
> 
> Because it's not a frequent need. Actually, I've never needed to know how
> many key-value pairs there are when I'm not using an array (ie, indexed by
> natural numbers).

Funny, I needed it yesterday. A benchmark script requests a number of
objects, and measures time until all objects have been received.
Outstanding requests are indexed by an identifier in a table, when the
table size (size:=number of pairs) is zero, all have been received, and
benchmark result is calculated.

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

Our C code does this a lot, too (~300 places), using hash-maps to track
active work items. Much of that code I would like to rewrite in lua,
tables would be easier to work with, and we'll add table.size() if we
do.

> > Perhaps the C implementation of Lua counts the number of pairs as they
> > are added and removed, but this count is not exposed in Lua?
> 
> No, it does not. See
> 	http://www.lua.org/source/5.1/lobject.h.html#Table

Wouldn't it be easy, and very low-overhead, to increment and decrement a
count for every add/remove? My countpairs() is O(n) :-(

Also, I wonder if some of the FAQs about what the size of a table is,
and whether its meaningful, and about how the table has to have
contiguous integral keys starting at 1 in order for the size to mean
anything, etc., etc., would be addressed by changing the rule to be:

   #t is the number of pairs in t. always.

Its hard to be clearer than that.

The table may be able to apply certain optimizations internally in how
it organizes pairs with array-like key sequences. Thats great, but what
is the advantage of having this optimization visible to the API?

The only thing I can think of it allows simultaneous use of the same
table using array-like keys with a size specific to them, and then a
separate use of the hash-part that doesn't effect the array size. Yuck.
This strikes me as obscure, error-prone, and less common than wanting to
know how many pairs, total, are in a table.

Cheers,
Sam

Lua 5.1.1  Copyright (C) 1994-2006 Lua.org, PUC-Rio
> t={}
> t[5] = t
> = #t
0
> t[4] = t
> t[3] = t
> return  #t
0
> t[2] = t
> t[1] = t
> return  #t
5
> t[1] = nil
> return  #t
5