[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: Better way to code an iterator function?
- From: "Lawrence E. Bakst" <ml@...>
- Date: Sat, 24 Oct 2009 03:56:44 -0400
Thanks for this and to the other poster as well who suggested the same thing. Very clean and I get it. FWIW one thing I was missing is that while you can return 3 values (f, state, var) to set up an iterator, you don't have to return/use all 3, which I guess is obvious, but somehow I missed it.
At 11:18 AM +0100 10/23/09, Duncan Cross wrote:
>On Fri, Oct 23, 2009 at 6:42 AM, Lawrence E. Bakst <ml@iridescent.org> wrote:
>> 1. Is there a better, shorter, cuter, or cooler way to code the example below?
>>
>> 2. I guess something I didn't try was to "deep copy" paths, use that as the state, and then remove one element at a time from the state.
>>
>> 3. This is probably FAQ, but I couldn't find much with a quick search on Google.
>>
>> I miss C's pre/post inc/dec operators and I can't be the only one. Is there any way to make inc and dec functions that increment or decrement the number passed in and return the previous value? Seems difficult in a language that only has pass by value for numbers and strings.
>
>Right, it isn't possible in standard Lua.
>
>> 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"};
>
>It seems to me that what you want is to -either- use a dedicated local
>function, like this:
>
> -- example 1
> local function it_paths_aux(state)
> local idx = state.idx + 1
> state.idx = idx
> return state.paths[idx]
> end
>
> function it_paths(paths)
> return it_paths_aux, {paths=paths, idx=0}
> end
> -- end example 1
>
>...or if don't mind generating a closure each time, using an upvalue
>to store the current state:
>
> -- example 2
> function it_paths(paths)
> local idx = 0
> return function()
> idx = idx + 1
> return paths[idx]
> end
> end
> -- end example 2
>
>-Duncan
--
leb@iridescent.org