[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: iterating over ... ?
- From: Patrick Donnelly <batrick@...>
- Date: Mon, 4 Apr 2011 15:43:46 -0400
On Mon, Apr 4, 2011 at 9:48 AM, Jerome Vuarand <jerome.vuarand@gmail.com> wrote:
> You can use coroutines, but I don't think it's a better solution. For example:
>
> local function step(head, ...)
> if head==nil then
> return
> end
> coroutine.yield(head)
> return step(...)
> end
>
> local function init(...)
> coroutine.yield()
> return step(...)
> end
>
> local function vararg(...)
> local c = coroutine.wrap(init)
> c(...)
> return c
> end
>
> for value in vararg(1, 2, 3) do
> print(value)
> end
You can also handle nils:
local function step (n1, n2, v, ...)
if n1 > n2 then
return nil
else
coroutine.yield(n1, v)
return step(n1+1, n2, ...)
end
end
local function init (...)
coroutine.yield()
return step(1, select("#", ...), ...)
end
function vararg(...)
local c = coroutine.wrap(init)
c(...)
return c
end
Then you iterate using:
for i, v in vararg(a, b, c) do
end
--
- Patrick Donnelly