lua-users home
lua-l archive

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


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