Control flow
if-then-else
A simple example of if
statement:
if a > b then
print("a is greater than b")
end
if-else
statement example:
if a > b then
print("a is greater than b")
else
print("a is less or equal to b")
end
A chain of if-else
statements is implemented with elseif
statement:
if a > b then
print("a is greater than b")
elseif a < b then
print("a is less than b")
else
print("a is equal to b")
end
while
While is a loop statement which checks a given condition before every iteration and executes the loop block if the condition is true:
n = 1
while n < 100 do
n = n + n * n
print(n)
end
repeat-until
Repeat-until statement, on the other hand, checks a given condition after every iteration. Also, loop continues if the condition is false:
n = 1
repeat
n = n + n * n
print(n)
until n >= 100
Running the example above you'll see the following output:
2
6
42
1806
The last number is greater than 100, however we see it in the output. That happens because repeat-until
statement checks the condition after the iteration, not before.
for
There are different ways to use for
loop. The simplest one:
for n = 1, 5 do
print(n)
end
Running the example above you'll see in the output:
1
2
3
4
5
As you see, both ends of the range are included into enumeration. Incremental step equals to 1.
You can specify the incremental step explicitly:
for n = 1, 5, 2 do
print(n)
end
1
3
5
This step can be negative:
for n = 10, 0, -1 do
print(n)
end
range-based for loop
To iterate a table you usually use for
with in
statement:
person =
{
name = "Alice",
age = 16,
website = "alice.myblog.com"
}
for key, value in pairs(person) do
print(key .. ": " .. value)
end
name: Alice
age: 16
website: alice.myblog.com
Another example:
names = {}
names[0] = "Clare"
names[1] = "Alice"
names[2] = "Bob"
names[3] = "Tiffany"
names[10] = "Sam"
for index, name in ipairs(names) do
print(index .. ": " .. name)
end
1: Alice
2: Bob
3: Tiffany
Note that in the first example we've used pairs
while in the second it's ipairs
. What's the difference?
pairs vs ipairs
Both of these are some sort of range views. To iterate a table you need to use one of these.
pairs
is a key-value view which works with all kind of keys and used for associative tables. The order of enumeration is unspecified in this case.
ipairs
is an indexed view. It iterates a given table like that:
- The indices should be integer. Non-integer indices are ignored;
- The first index should be 1;
- Each subsequent index should be next integer;
- Iteration stops when no subsequent index is found;
- Pairs are ordered by the index in ascending order.
That's why both Clare and Sam are ignored in the last example.