Lua Iterators: Comprehensive Guide

Lua iterators allows you to iterate over complex data structures such as tables, arrays, and even user-defined data types in a clean, concise, and efficient manner.

Iterators can be used to simplify code, reduce errors, and make code more readable and maintainable.

Lua iterators can be classified as stateless or stateful based on whether or not they maintain any internal state.

The focus of this article is going to be iterators in Lua.



Lua Iterators Stateless

A stateless iterator is one that does not maintain any internal state and simply returns the next value in the sequence.

Each call to the iterator function is independent of any previous call.

Here is an example of a stateless iterator:

Example: 

function values(t) local i = 0 return function() i = i + 1 return t[i] end endt = {2, 4, 6, 8, 10} for v in values(t) do print(v) end

Some built-in stateless iterators are:

ipairs()

This function iterates over arrays with integer keys in numerical order.

An array is passed to the function as an argument, and it returns an iterator function that can be used to loop over array elements.

Below example is used to demonstrate the ipairs function where the table is passed as an argument:

Example: 

local arr = {"one", "two", "three"}for i, fruit in ipairs(arr) do print(i, fruit) end

pairs()

This function is used to iterate over tables.

It returns an iterator function that iterates over the key-value pairs in a table.

Following example deals with the pairs function in Lua which takes the table as an argument:

Example: 

local arr = {"one", "two", "three"}-- Iterate over the key-value pairs in the table for key, value in pairs(arr) do print(key .. " – " .. value) end

next()

It allows you to iterate over a table.

It takes two arguments: a table and a key, and returns the next key-value pair in the table following the given key.

If the given key is nil, next() returns the first key-value pair in the table.

Let’s explore this function using as example:

Example: 

t = {one = 1, two = 2, three = 3}-- using next() with nil as the key returns the first key-value pair k, v = next(t, nil) print(k, v) -- prints "one 1"-- using next() with the first key returns the second key-value pair k, v = next(t, k) print(k, v) -- prints "two 2"-- using next() repeatedly returns each subsequent key-value pair k, v = next(t, k) print(k, v) -- prints "three 3"

string.gmatch()

The string.gmatch() function in Lua takes a string and a pattern as input and returns an iterator function that can be used to iterate over all matches of the pattern in the given string.

The iterator function generates each match on the fly, based on the input string and pattern provided to it.

Following example illustrates the string.gmatch function in Lua:

Example: 

local str = "MrExamples" local pattern = "%a+"local iterator = string.gmatch(str, pattern)for match in iterator do print(match) end

Lua Iterators Stateful

Lua stateful iterator is one that maintains some internal state between calls to the iterator function.

The state can be used to keep track of where the iterator is in the sequence or to perform some other function.

Let’s take a look at an example of stateful iterator:

Example: 

function range(start, stop, step) local i = start – step return function () i = i + step if step > 0 and i > stop then return nil elseif step < 0 and i < stop then return nil else return i end end endfor x in range(1, 10, 2) do print(x) end

Some built-in stateful iterators are:

coroutine.wrap()

It creates an iterator function that can be resumed with the coroutine.resume() function.

No arguments are required for the iterator function, and multiple values are returned by the coroutine.

As soon as the coroutine function returns, the iterator function also returns, indicating that the iteration is complete.

Following examples showcases the implementation of coroutine.wrap() function:

Example: 

function even_numbers(limit) local i = 0 return coroutine.wrap(function() while i < limit do i = i + 2 coroutine.yield(i) end end) endfor n in even_numbers(10) do print(n) end

io.lines()

This function returns an iterator to iterate over the lines of a file.

It takes a filename or an open file handle as its argument and returns an iterator that can be used to loop over the lines of the file.

Following code snippet portrays the io.lines() function in Lua:

local file = io.open("my_file.txt", "r")

for line in io.lines(file) do
print(line)
end

io.close(file)

In above example, we open a local file named my_file.txt for reading and used the io.lines() function to loop over the lines of the file.

Each line is returned as a string and printed to the console.

Finally, we close the file handle using the io.close() function.

To stay up-to-date with all the latest advancements in Lua, subscribe to our newsletter below.

We value your feedback.
+1
0
+1
0
+1
0
+1
0
+1
0
+1
0
+1
0

Subscribe To Our Newsletter
Enter your email to receive a weekly round-up of our best posts. Learn more!
icon

Leave a Reply

Your email address will not be published. Required fields are marked *