Lua Programming/How to Lua/if conditionals

From Wikibooks, open books for an open world
Jump to: navigation, search

An if statement can be used to execute a block of instructions based on whether or not a condition is considered to be true. The simplest form of if statement consists of the keywords if followed by an expression and a block of statements surrounded by the then and end keywords.

if (x < 5) then
  print("x is less than 5")
end

If expression evaluates to anything other than nil or false -- including the number 0 or the empty string -- the block of statements within the then and end keywords will be executed. Otherwise, the block will be skipped and control will move to the first statement after the end keyword. In the example above, the string "x is less than 5" will only be displayed if x was set to a number which is less than but not equal to 5.

Else Block[edit]

An else block can be added to designate a block of instructions that is to be executed when the if expression evaluates to nil or false. The keyword else is used to separate the block of statements that are run when the if condition is false (the else block) from the block of statements that are executed when the if condition is true (the then block). The final end keyword designates the end of the else block.

if (x < 5) then
  print("x is less than 5")
else
  print("x is greater than or equal to 5")
end