lua-users home
lua-l archive

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


Am 25.06.2016 um 20:34 schröbte Roberto Ierusalimschy:
As I've mentioned elsewhere I'm not a big fan of the `table.pack()`
function, but one nice thing about it is that we now have an
official way to represent sparse tables (with that extra `n` field
that `table.pack()` sets). Strange thing is that `table.unpack()`
*does not* honor that `n` field although those two functions appear
to be inverses of each other.

Unlike table.pack, which creates a new table (and therefore has
complete control over it), table.unpack works with other-people's
tables. Therefore, it seems better not to assume particular policies on
how those tables work.

`table.unpack()` already assumes a particular policy: proper sequences unless `__len` is defined. So `table.unpack()` could be a more natural mirror function of `table.pack()` simply by setting a metatable on the packed `t.n` table, which -- as you said -- is created by the `table.pack()` function and completely under its control. That part doesn't need any new/different assumptions about tables than we have right now in Lua 5.3. `table.unpack()` already respects `__len` after all.

So far I think this is a no-brainer.

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?

If you want to unpack a "table.pack" table, just
call table.unpack(t, 1, t.n).

-- Roberto


Philipp