Basic Functions

The section contains functions to create iterators from Lua objects.

fun.iter(array)
fun.iter(map)
fun.iter(string)
fun.iter(gen, param, state)
Returns

gen, param, stateiterator triplet

Make gen, param, state iterator from the iterable object. The function is a generalized version of pairs() and ipairs().

The function distinguish between arrays and maps using #arg == 0 check to detect maps. For arrays ipairs is used. For maps a modified version of pairs is used that also returns keys. Userdata objects are handled in the same way as tables.

If LUAJIT_ENABLE_LUA52COMPAT 1 mode is enabled and argument has metamethods __pairs (for maps) or __ipairs for (arrays), call it with the table or userdata as argument and return the first three results from the call 2.

All library iterator are suitable to use with Lua’s for .. in loop.

> for _it, a in iter({1, 2, 3}) do print(a) end
1
2
3

> for _it, k, v in iter({ a = 1, b = 2, c = 3}) do print(k, v) end
b 2
a 1
c 3

> for _it, a in iter("abcde") do print(a) end
a
b
c
d
e

The first cycle variable _it is needed to store an internal state of the iterator. The value must be always ignored in loops:

for _it, a, b in iter({ a = 1, b = 2, c = 3}) do print(a, b) end
-- _it is some internal iterator state - always ignore it
-- a, b are values return from the iterator

Simple iterators like iter({1, 2, 3}) have simple states, whereas other iterators like zip() or chain() have complicated internal states which values senseless for the end user.

Check out Under the Hood section for more details.

There is also the possibility to supply custom iterators to the function:

> local function mypairs_gen(max, state)
    if (state >= max) then
            return nil
    end
    return state + 1, state + 1
end

> local function mypairs(max)
    return mypairs_gen, max, 0
end

> for _it, a in iter(mypairs(10)) do print(a) end
1
2
3
4
5
6
7
8
9
10

Iterators can return multiple values.

Check out Under the Hood section for more details.

1

http://luajit.org/extensions.html

2

http://www.lua.org/manual/5.2/manual.html#pdf-ipairs

fun.each(fun, gen, param, state)
iterator:each(fun)
Returns

none

Execute the fun for each iteration value. The function is equivalent to the code below:

for _it, ... in iter(gen, param, state) do
    fun(...)
end

Examples:

> each(print, { a = 1, b = 2, c = 3})
b 2
a 1
c 3

> each(print, {1, 2, 3})
1
2
3

The function is used for its side effects. Implementation directly applies fun to all iteration values without returning a new iterator, in contrast to functions like map().

See also

map(), reduce()

fun.for_each(fun, gen, param, state)
iterator:for_each(fun)

An alias for each().

fun.foreach(fun, gen, param, state)
iterator:foreach(fun)

An alias for each().