In every program we need sometimes to control the program flow. if-statements, loops and similar structures can help with the task. Lets learn the control structures in Lua.

Control structures

Control structures in Lua brings back old days of Pascal programming with similar structures.

Loops that are available in Lua are: repeat … until and while .. do .. end. There’s also a for-loop or as it called here for-statement.

If is also a bit different then in C-like languages (C, C++, C#). The form goes like this: ifthen end. If additional else if is to be added it is denoted with elseif keyword.

The for-statement comes in to flavours and basically the second one is known as foreach in C#.

for v = e1, e2, e3 do block end

e1 is the starting index, e2 is the limit and e3 controls how much the index is changing in each loop. e3 is optional and it will be by default 1.

The foreach form goes like this

for var_1, ···, var_n in explist do block end

This version is more powerful than C# one. If instead of io.lines we would have a function that returns multiple objects, we could assign them to separate variables in the for-statement. Check this example form Lua documentation

More on statements in chapter 3.3 of the Lua documentation.