lua-users home
lua-l archive

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


2009/6/10 Sam Roberts <vieuxtech@gmail.com>:
> 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 don't see the following explicitly mentionned in the other replys,
maybe I missed it and I apologize if I did.

You use #... as if it was returning the number of values in ..., but
that is actually applying the # operator to the first value in ...,
and in your case it's the string "red", so it happens to be the good
value (3), but not what you intended. As mentionned by other replies
the correct way to get the number of arguments is select('#', ...).