Conditional structures allow scripts to perform actions when specific conditions are met. These conditions can be checked with the relational operators summarized here:
||Not equal to||
||Greater than or equal to||
||Less than or equal to||
if — then
then statement executes a block of code if a specific condition is true. For instance:
Note that Lua considers the “absence of true” as “false.” This means that both
nil will evaluate as non-true:
elseif — then
then statement to an
then structure lets you check if alternative conditions are true, assuming the preceding conditions are false. Lua will go from top to bottom, stop at the first true condition it encounters, and execute its block of code.
Finishing a conditional structure with
else lets you execute a block of code if none of its preceding conditions evaluate to true. In the following example, both
10 > 100 and
10 > 25 are false, so those blocks of code will not execute but the
else block will.
Conditional loops let you execute specific code while a condition is true, or repeat code until a condition becomes true.
while — do
do loop evaluates if a condition is true or false. If false, the loop ends and the code following it continues to execute. If true, the code between
end executes and the true/false condition is reevaluated afterward.
repeat — until
until loop repeats until a certain condition is met. Note that the code between
until is executed at least once because the conditional test is performed afterward.
Using Logical Operators
To avoid repetitive conditional tests in a sequence, use the logical operators
or to perform multi-condition tests. For example, the following structure tests that two conditions are true:
Logical operators can also be combined to perform more complex logical tests. For instance, the following code checks whether two conditions are true or a third condition is true:
While the relational operators can be “flipped” to test for non-truth conditions, the logical operator
not is useful for testing the “absence of true” (either
not operator can also test for the opposite of an entire multi-condition statement. For example, the following code confirms that there are not more than 25 goblins nor is the player’s experience level less than 5.