lua-users home
lua-l archive

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


On Mon, Jun 1, 2015 at 3:07 PM, Roberto Ierusalimschy <roberto@inf.puc-rio.br> wrote:
> This was meant to be a question about tracking the physical number of
> non-nil entries in the internal table data structure. [...]
>
> This being the case, most of the gotchas mentioned above seem to evaporate,
> and the only reason not to do that that I can see is that it makes *ALL*
> table writes a tiny bit more expensive. [...]

Another reason not to do so is that it makes '#' mostly useless for
sequences (which are the only reason for its existence).

Oh, I don't know that's necessarily true. In the case where t is a sequence (with no non-numeric keys), then #t == numentries(t), sure. But they are answering fundamentally different questions. It's kinda like saying that pairs() is a bad idea because it makes ipairs() redundant for sequences.

I could definitely see a use for knowing the total number of things in a table, versus knowing the sequence length of a table (Andrew Starks' "sequence with properties"). Plus `#' uses the __len metamethod if it exists, which means you can get a non-zero length for a table that technically doesn't have any physical entries of any sort under any key.

> mt = { __len = function(t) return 5 end }
> mt.__index = mt
> t = {}
> setmetatable(t, mt)

--
Brigham Toskin