lua-users home
lua-l archive

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


Hi,

may not be the fastest way, but a recursive unpack should
work?

function unpack( table, nextidx )
  if nextidx == nil then
    nextidx = 1
  end

  if table.n > 1 then
    table.n = table.n - 1
    return table[nextidx], unpack(table, nextidx + 1)
  else
    return table[nextidx]
  end
end


Regards,

 Michael Flad


> Von: owner-lua-l@tecgraf.puc-rio.br
> [mailto:owner-lua-l@tecgraf.puc-rio.br]Im Auftrag von John Belmonte
> Gesendet: Sonntag, 4. März 2001 11:57
> An: Multiple recipients of list
> Betreff: vararg asymmetry

> Usually with Lua programming we discover something new and
> think, "wow I
> didn't realize that could be done".  But sometimes the
> opposite occurs...
>
> I want an interface for packing/unpacking binary data that
> works like this:
>
>     data = pack(template, val1, val2, ..., valn)
>     val1, val2, ... valn = unpack(template, data)
>
> However as far as I know there is no way to implement unpack
> in Lua because
> the output of a function (that is, the number of values)
> cannot be generated
> by program.  (I do realize that I can just use tables.  Also,
> I suppose it's
> possible to generate the required code on the fly and use
> dostring but that
> is not very reasonable.)  On the other hand, the input of a
> function can be
> generated easily (by making a table and using call) so there
> seems to be a
> lack of symmetry in the standard library.  What I'm trying to
> do with unpack
> is not so bizarre.  In fact the function strfind in the
> standard library
> does the same thing, so it also could not be implemented in
> Lua.  Maybe
> adding a function like this would be useful:
>
>     expand (table)
>
>     Return elements of table with indexes 1..getn(), in
> order, as individual
> values.
>
>
> -John