lua-users home
lua-l archive

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


Hello,

I have some code where I have to perform some process over an already known set of data. For the sake of not duplicating the code process, I want to iterate over each item in a loop. I know a very simple way of doing this is to store each item in a table and iterate with ipairs(). However, as an exercise, I wanted to code my own iterator with a vararg function, to be used as follows:

-- return an iterator that will pass all received arguments in sequence
iterate_over = function( ...)
    local items, count = {...}, select( '#', ...)
    local iterator = function( _s, _key)
        if _key >= count then
            return nil
        end
        _key = _key + 1
        return _key, items[_key]
    end
    return iterator, nil, 0
end

for _, item in iterate_over( a, b, c) do
  do_something( item)
end

The idea was to avoid the creation of a table just for the purpose of being able to iterate over its contents.
Unfortunately, it would seem that I must generate a table to enclose the vararg list anyway, so that I can index it. Is there something I missed that could help avoid
1. the creation of this items table?
2. calling select just to get the number of items, thus losing time pushing the full ... again on the stack?

TBH, I currently have 2 such items, so I can live with these performance hogs :-). But I would like to know if there is a better solution, for my own education.


--
Benoit.