lua-users home
lua-l archive

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

On Jun 25, 2016, at 2:38 PM, Philipp Janda <> wrote:

The more interesting question is: Should the rest of the table library work on the kind of tables returned by `table.pack()`? Most functions respect `_len` (and `__(new)index`), but in case of `table.insert()`, `table.remove()`, and `table.move()` you have to *update* the length, which isn't possible with `__len` alone. Originally intended or not, the `table.pack()` tables are now a prototype for potentially sparse arrays in Lua. Is this a more useful format for arrays in Lua than sequences? Should Lua encourage using `t.n` tables instead of sequences for most/all array needs?

Hence my earlier post. Of course, *every* Lua table is a sparse array, though in many cases its empty. That is, unless you *define* a sparse array as a table having an “n” key (and hope no-one uses this perfectly normal key for something else…). So what use is # or “.n” anyway? Primarily, it gives an upper bound for iteration, sorting etc. Viewed like this, I think sparse length needs to be first-class, not just conventional. So everyone can work with known length arrays, either in Lua or C, and can use __len as needed. And as an added benefit, #t works in O(1) time instead of O(log N) time (assuming no metatable, of course).