lua-users home
lua-l archive

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


2016-07-25 6:59 GMT+02:00 nobody <nobody+lua-list@afra-berlin.de>:
> On 2016-07-25 03:58, Rodrigo Azevedo wrote:
>> DISCLAIMER: I'm just wondering about this topic
>>
>> table.pack() is used to pack "the stack", that can hold nils. To accomplish
>> this behaviour it uses the  ".n" field (I'm not analysing the merit here).
>> Since this is somewhat arbitrary,

Though arbitrary, it is not more so than using __len instead of __size.
'pack' is a relatively new function in Lua, but its roots go back to Lua 3.0,
when vararg functions were introduced. Inside the body of a vararg
function there was an automatically constructed table 'arg' whose
value was precisely the table later obtainable as 'pack(...)', i.e.
arg.n gave a count of the number of arguments.

> You cannot compute the length, so you have to store it somewhere.
> Walking outwards, we have the following options:
>
> (a) In the table: that's what we currently have with 'n' (just without
> the metatable/__len).
>
> (b) In the metatable: That means you need a separate metatable per
> table, creating more garbage.
>
> (c) "globally" accessible (e.g. in a table in an upvalue of the
> metamethod(s)):
>
> So you can essentially choose between warts, garbage factory, or space
> hog.  The current choice of Lua/table.pack is warts.

There is one other possibility: 'pack' could return 'n' as a second
(or even a third [1]) return value.The user that does not need the
argument count (e.g. being  sure that there are no holes) can ignore it,
the one that does, can store it in a local variable. It's no more convenient
than tbl.n (you can always store tbl.n in a local variable and reuse 'n'
for your own purposes) but possible less warty.

[1] With second return value nil or 1, to be compatible with the arguments
expected by table.unpack.