[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: Better way to code an iterator function?
- From: Jerome Vuarand <jerome.vuarand@...>
- Date: Fri, 23 Oct 2009 12:12:56 +0200
2009/10/23 Lawrence E. Bakst <ml@iridescent.org>:
> 1. Is there a better, shorter, cuter, or cooler way to code the example below?
>
> [...]
>
> function it_paths(paths)
> local function next(state, var)
> if (state.idx > #paths) then return nil end;
> state.idx = state.idx + 1;
> return paths[state.idx - 1];
> end
> local state = {idx = 1};
> return next, state, "";
> end;
>
> function process_random_files(paths)
> for path in it_paths(paths) do
> print(path);
> end
> end
>
> process_random_files{"foo", "bar", "baz", "quuz"};
I don't know if it's cuter or cooler, but with an upvalue to store the
state it's shorter :
function it_paths(paths)
local index = 0
return function()
index = index + 1
return paths[index]
end
end