[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: unpack() behaviour not as documented
- From: "Thomas Harning Jr." <harningt@...>
- Date: Wed, 10 Jun 2009 17:10:53 -0400
On Wed, Jun 10, 2009 at 4:48 PM, Sam Roberts<vieuxtech@gmail.com> wrote:
> 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
One useful thing to note is that if you want to pack variable
arguments into a table and not lose track of the end, you can do the
following:
local packed = {n = select('#', ...), ...}
That way you store the number of var-args (what select('#') does) and
keep all the values that were in there.
... now... if you don't need to persist the var-arg, it might be best
to take the var-arg and iterate over it, either using select, or a
lisp-like handling.
Ex:
local function for_each_vararg(fn, value, ...)
fn(value)
if select('#', ...) > 0 then
return for_each_vararg(fn, ...)
end
end
... or if you don't care about nils
local function for_each_vararg(fn, value, ...)
if not value then return end
fn(value)
return for_each_vararg(fn, ...)
end
--
Thomas Harning Jr.