SoFunction
Updated on 2025-04-08

A brief summary of the control structure (process control) in Lua

In Lua, all control structure blocks are ended with end.
The expression result of the control structure can be any value. In Lua, only false and nil are false, and other values ​​are true.

1. if

Copy the codeThe code is as follows:

if conditions then
    ...
end;  
 
if conditions then
    ...
else
    ...
end;
 
if conditions then
    ...
elseif condition then
    ...
else
    ...
end;

The then keyword is used to mark the beginning of a conditional code block.

2. repeat

Copy the codeThe code is as follows:

repeat
    ...
until conditions

The repeat keyword is used to mark the beginning of a code block, and until is used to mark the end of a code block. The conditional expression of the control structure is located after the until keyword.

3. while

Copy the codeThe code is as follows:

While conditions
do
    ...
end

Repeat and while control structures are similar, and both can loop through a piece of code until a certain condition is met.
The repeat control structure will determine the condition at the last time, and the code block will be executed at least once.
The while control structure first determines the condition. If true, the code block will be executed, or it may never be executed.
The while control structure uses the do keyword to mark the beginning of the program block.

4. for

Copy the codeThe code is as follows:

for variable = initial value, end point value, step length
do
    ...
end
 
for variable 1, variable 2, ... variable n in table or enumeration function
do
    ...
end

The number of loops is determined only at the first execution. The initial value, end value, and step size will be calculated only once and before the loop is executed.
The variables in the loop structure are local variables and are cleared once the loop body is finished.

5. break

The break statement is used to exit the current loop. It cannot be used outside the circulation body.

6. return

return is used to return the result from the function. After a function naturally ends, there will be a default return.