[Date Prev][Date Next][Thread Prev][Thread Next]
- Subject: Re: Project lead nominations for standard libraries?
- From: Dirk Laurie <dpl@...>
- Date: Mon, 3 Jan 2011 11:38:33 +0200
On Sat, Jan 01, 2011 at 10:23:17PM +0200, David J. Slate wrote:
> For what they're worth, I thought I would add my impressions to all
> the other posts about the '#' operator:
> As applied to strings it does, returning unambiguously the length
> of the string. But applied to tables, it produces a sensible result
> only for arrays or lists with integer indices beginning with 1 and
> without "holes". Intuitively, I would have expected a "length
> operator" as applied to an associative table to produce a count
> of its keys, regardless of what kind of table it was.
#t works perfectly for annotated lists, giving the count of the
anonymous items. That's what it is designed for, and it matches
perfectly with table.insert and table.remove, which are not supposed
to be used on other kinds of tables. Many people use this structure,
and it is not counter-intuitive for them.
Your intuition belongs to tables with no anonymous items. You are
allowed to override __len for such tables.
function slate_len(t) local s=0
-- counts the number of keys in a table
for k in pairs(t) do s=s+1 end
return s end
O(1) implementation is possible if really needed, requires work on
Seems to me we have the best of both worlds: something that works
well in a well-defined and quite common case, as well as the freedom to
modify it when something else is appropriate.
I don't support Axel's idea to force the user to define __len.
Maybe have a bit more in the reference manual about table functions
being well-behaved only for annotated lists. People do read the
reference manual, don't they? Surely? :-?