PcoWSkbVqDnWTu_dm2ix
We use cookies on this site to enhance your user experience

Conditional Structures

Conditional Structures

Oct 23 2019, 2:22 PM PST 10 min

Conditional structures allow scripts to perform actions when specific conditions are met. These conditions can be checked with the relational operators summarized here:

Operator Description Example
== Equal to 3 == 5  →  false
~= Not equal to 3 ~= 5  →  true
> Greater than 3 > 5  →  false
< Less than 3 < 5  →  true
>= Greater than or equal to 3 >= 5  →  false
<= Less than or equal to 3 <= 5  →  true

Conditional Tests

if — then

The basic ifthen 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 false and nil will evaluate as non-true:

elseif — then

Adding an elseifthen statement to an ifthen 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.

else

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

Conditional loops let you execute specific code while a condition is true, or repeat code until a condition becomes true.

while — do

The whiledo 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 do and end executes and the true/false condition is reevaluated afterward.

repeat — until

A repeatuntil loop repeats until a certain condition is met. Note that the code between repeat and until is executed at least once because the conditional test is performed afterward.

Using Logical Operators

Multi-Condition Tests

To avoid repetitive conditional tests in a sequence, use the logical operators and and 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:

Non-Truth Tests

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 false or nil).

The 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.

Tags:
  • coding
  • lua
  • logic
  • condition