lua-users home
lua-l archive

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


Hi Alexander,

On Fri, Jan 22, 2010 at 1:59 PM, Alexander Gladysh <agladysh@gmail.com> wrote:
> Hi, list!
>
> I'm glad table.pack() is here, as it is one of the functions I always
> write myself.
>
> 5.2 pack() could be defined as follows:
>
>    function pack(...)
>      return { n = select("#", ...), ... }
>    end
>
> We need to store number of arguments, to be able to call unpack()
> safely if arguments contain nils (or table size definition will get
> us).
>
> Today I looked at my code, and realized that my pack has slightly
> different protocol:
>
>    function pack(...)
>      return select("#", ...), { ... }
>    end
>
> Note that it is probably better to swap size and table:
>
>    function pack(...)
>      return { ... }, select("#", ...)
>    end
>
> So user who do not need size, would not be forced to create a variable for it:
>
>    local t = pack(...)
>
> I do not argue for this protocol just because it is mine — it is not a
> problem to switch to a new one.

The problem with table.pack is it lacks functionality that is very
complicated and expensive in pure Lua. Packing values into a new table
is easy (the common idiom: {n = select("#", ...); ...}). Packing
values into an existing table is hard. You must iterate over the
vararg using select which is expensive and ugly. As I've said
elsewhere, what we really need is table.pack to work on a table passed
to it and take an index on where to append the values to the array
(usually, the very beginning). Something like this captures all use
cases I can think of:

table.pack(t, n, ...)

where the length of t is truncated to length n-1 (luaH_resize?) and
the variable number of arguments are appended. It may even make sense
to have an upper bound on where to pack just like table.unpack.

> That being said, I wonder, which one is better and why... What do you think?

So to answer your question, neither :)

-- 
-Patrick Donnelly

"Let all men know thee, but no man know thee thoroughly: Men freely
ford that see the shallows."

- Benjamin Franklin