lua-users home
lua-l archive

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

2016-08-06 22:21 GMT+02:00 Soni L. <>:
> So we have string.len but no table.len.
> Can we get table.len? As with string.len, it should be equivalent to a
> type-checking #.

See 4.a in the summary below.

We have had several threads [1-5] that started wherever and
wound up in some kind of discussion on __len and the table
library. As my first and only contribution to yet another such
thread, I'll summarize my position on those.

1. Ideas from present and previous versions of Lua that I like a lot:
  a. A hidden length field for each table, accessible by a specialized
mechanism (table.pack, getn, setn) but not by raw indexing (which
includes `next` and raw `pairs`).
  b. A default algorithm for calculating length.
  c. A mechanism for allowing the user to override the default algorithm.
  d. Availability of explicit range limits on table functions.
2. Ideas from present and previous versions of Lua that I like less:
  a. An explicit 'n' field for length, no matter what it might be called.
  b. Non-availability in the table library of the default algorithm for
calculating length.
  c. Non-availability of explicit range limits on some table functions.
3. The ideal "length" function.
  a. First check __len.
  b. If there is no __len, check the hidden length.
  c. If the hidden length has not been set, use the default algorithm.
4. Other 'table' goodies that would be nice.
  a. '': Ths would perform the much maligned length
calculation that has been in place for some time, with a name that
warns you that it is a subtle concept. I suggested this in [2] on
7 July 2016.
  b. 'j' parameter in table.remove(tbl[,i[,j]]).
  c. `i` and `j` parameters in table.sort(tbl,[comp,[i,[,j]]]).

I thank you for suggesting in [1] on 25 June that __len could be
a number (and apologise belatedly for my flippant reply then,
before really thinking on it). It made me research the history of
length in old Lua manuals and thus helped me to find out that
there actually was a hidden table length once.

[1] 'table' as fallback for tables
[2] New array type?
[3] Quest: real world "Lua array with holes" usage
[4] The Undefined Country
[5] (I probably missed some)