Iterators
Iterators are used to loop through a collection of data. They are also used to repeat processes a preset or infinite amount of times.
Iteration Types
In Lua, there are multiple ways to iterate through and/or repeat code. Some iteration methods are intended for iterating through arrays, while others can be used to repeat
a command until/while a condition is met. Below are some examples of conditional iterations.
While
A common form of iteration is the “while” loop, in Lua this form of iteration is also implemented with the while
keyword. However, the body of the loop is framed by the do
and end
keywords, as opposed to the curly braces that are used in many other languages.
In addition to the familiar while loop format, there is also the repeat
-until
syntax that can be used to serve the same purpose.
-- This iteration will repeatedly execute it's provided code until the CONDITION becomes false.x = 2while x > 0 doprint("x is still greater than 0!")x -= 1endprint("x is no longer greater than 0!");-- repeat TASK until CONDITION-- This iteration will repeat its provided task until the required CONDITION becomes truei = 1repeati = i + 1print(i) -- 1, 2, 3, 4, ..., 20untili == 20 -- Stops iteration when 'i' becomes equivalent to 20
For
It’s also possible to create a loop, such as iterating through a list’s contents, by using the phrase for i = n1, n2, n3 do
. This method of iteration will not automatically fetch index and value pairs, but will instead repeat a task a specified amount of times. The n
values represent the commonly used start, stop and increment values in a typical for
loop.
--- Repeat the "print" method by using this type of iteration.for i = 1, 3 doprint(i) -- 1, 2, 3end--[[Alternatively, this can be flipped backwards by usingan optional third parameter within an iteration.This third parameter will control how 'i' will increment itself per iteration.]]--for i = 1, 3, -1 doprint(i) -- 3, 2, 1end
As mentioned, iterations can be used to loop through an array. For this, the global keyword pairs
is used loop through an array in order.
list = {"🌽", "🥦", "🍄"}for Index, Value in pairs(list) doprint(Index) -- 1, 2, 3print(Value) -- 🌽, 🥦, 🍄end
Looking to contribute?
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.