lua-users home
lua-l archive

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


On Wed, Jun 10, 2009 at 9:48 PM, Sam Roberts<vieuxtech@gmail.com> wrote:
> Unpack's docs say unpack(t, i, j) does "return t[i], t[i+1], ...,
> t[j]", but I don't think it does this. Example follows.
>
> Generally, I don't see any way in lua to return a variable number of
> arguments, when some of those arguments will be nil.
>
> Can anybody suggest a way to implement the following so it works as intended?
>
> Cheers,
> Sam
>
> =========================
> stuff = {red=1, green=2, blue=3}
>
> function get_stuff(...)
>    local r = {}
>    for i,k in ipairs{...} do
>        r[i] = stuff[k]
>    end
>    return unpack(r, 1, #...) -- #... is 3 when there are 3 args to
> this function
> end
>
> red, magenta, green = get_stuff("red", "magenta", "green")
>
> print(stuff.red, " should eql ", red)
> print(stuff.magenta, " should eql ", magenta)
> print(stuff.blue, " should eql ", blue) -- but the [3] was not returned
>

I'm glad someone else has already replied sensibly as I was in danger
of making a bad joke about colour blindness, but I will add that if
you want to iterate over the varargs of a function, when some of them
may be nil, you have to use:

for i = 1,select('#', ...) do
  local k = select(i, ...)
  -- (stuff)
end

instead of:

for i,k in ipairs{...} do
  -- (stuff)
end

...as ipairs will stop on the first nil.

-Duncan