lua-users home
lua-l archive

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


Javier wrote:

i think a worthwhile feature for the next Lua (5.2?) would
be to make unpack() accept several arrays and return the
list of the concatenation of all.

I think I've wanted this functionality before (and I
presumably just rolled my own like Jerome did).

of course, if there's more than one array, there shouldn't
be any i,j parameters

I suppose unpack could check its arguments' types, but that
seems a bit ugly.

(who uses those, anyway?).

They're necessary for arrays with embedded nils:

-- Returns a function that prints MakePrinter's arguments:
function MakePrinter(...)
  local Args = {...}
  local ArgCount = select("#", ...)
  return function()
    print(unpack(Args, 1, ArgCount))
  end
end

Printer = MakePrinter(nil, "b", nil, nil)
Printer()
nil     b       nil     nil

Here's another use:

-- Returns an iterator that goes through all Len-long
-- subsequences of Arr:
function Subseqs(Arr, Len)
  local Pos = 0

  return function()
    Pos = Pos + 1
    if Pos + Len - 1 <= #Arr then
      return unpack(Arr, Pos, Pos + Len - 1)
    end
  end
end

Nums = {"one", "two", "three", "four", "five", "six"}
for Val1, Val2, Val3, Val4 in Subseqs(Nums, 4) do
  print(Val1, Val2, Val3, Val4)
end
one     two     three   four
two     three   four    five
three   four    five    six

(Plug: both examples are from Beginning Lua Programming.)

--
Aaron
Beginning Lua Programming: http://www.amazon.com/gp/product/0470069171/