lua-users home
lua-l archive

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


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

setmetatable(t,{__len=slate_len})

O(1) implementation is possible if really needed, requires work on
__newindex too.

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? :-?

Dirk