Skip to content

Lua Decision Making

Decision-making structures allow a program to execute different blocks of code based on whether certain conditions are true or false. This enables programs to react dynamically to different inputs or states.

The general flow of a decision-making structure is as follows: a condition (a boolean expression) is evaluated. If the condition is true, a specific block of statements is executed. If the condition is false, an alternative block of statements (often in an else clause) might be executed, or execution might simply continue after the decision structure if no alternative is specified.

In Lua, conditional expressions evaluate to true for any value except false and nil. This means that numbers (including 0), strings (including empty strings ""), tables, and functions are all considered true in a boolean context. Only false and nil are considered false.

Lua provides the following types of decision-making statements:

StatementDescription
if statementAn if statement consists of a boolean expression followed by one or more statements. The statements are executed only if the boolean expression evaluates to true (i.e., not false and not nil).
if...else statementAn if statement can be followed by an optional else statement. The else block executes if the boolean expression in the if statement is false (i.e., false or nil).
if...elseif...else statementUsed for testing multiple conditions. An if statement can be followed by one or more optional elseif statements and an optional else statement. Lua checks each condition sequentially; the block associated with the first true condition is executed, and the rest are skipped.
Nested if statementsYou can use one if or elseif statement inside another if, elseif, or else statement. This allows for more complex conditional logic.

We will explore these statements with examples in subsequent sections.