Lua else statements will execute a code block if every expression in the if-based control structure evaluates to false. If an else is included in a control structure, the else must go at the end.
if isSunny thenprint("Go outside!")else--This statement executes when every expression in--a control statment is false.print("Stay indoors.")end
A control structure will run different code blocks based on one or more true/false statements.
if isMonday thenprint("It's the beginning of a great week.")elseif isWednesday thenprint('Halfway through the week!")elseprint("Enjoy your day!")end
A Lua if statement is the first part of an if-based control structure. The if statement’s boolean expression is the first to be evaluated. An if statement does not need to be followed by any else or elseif statements.
if weather == "bad" thenprint("Bring a jacket!")end
A Lua elseif statement allows for additional boolean expressions to be evaluated in an if-based control structure. There is no limit to how many elseif statements are in a control structure, but elseif statements must be after the if statement and before a possible else statement.
if player == "track star" thenspeed = 10elseif player == "injured" thenspeed = 1elseif player == "training" thenspeed = 7elsespeed = 5end
A code block is a section of code. Control structures can be set up to determine whether or not they execute.
if runCodeBlock then-- The following indented code is a code block:print("Part of the code block.")print("Also part of the code block.")end
Boolean expressions evaluate to either true or false and are the conditional statements that make up a control structure. You can also include operators and variables in boolean expressions to make your logic more complex.
7 > 5 -- Evaluates to: true
The and operator is placed between two boolean expressions. It evaluates to true when both the left and right sides are true. Otherwise the and operator evalutes to false.
true and 5 == 5 -- Evaluates to true
The or operator is placed between two boolean expressions and evaluates to true if either side is true. Otherwise the or operator evalutes to false.
false or 5 == 5 -- Evaluates to: true
The not operator is placed before a boolean expression and evaluates to the inverse of the expression to its right.
not ("Hello" == "Hello") -- Evaluates to: false
Comparison operators compare two variables and either return true or false. The comparison operators in Lua are as follows: <, >, <=, >=, ==, ~=.
8 >= 10 -- Evaluates to: false