Table of Contents
Lua conditionals
Conditionals in Lua allow your script to make decisions based on whether certain conditions are true or false. These conditions are typically expressions that evaluate to a boolean value (true or false). Lua supports several types of conditional statements, like if, if-else, if-elseif-else
If statement
The if statement is the simplest form of conditional statement in Lua. It executes a block of code only if the specified condition evaluates to true.
Example:
local userplaysminiworld = true if userplaysminiworld == true then print("The user plays mini world!") end
Else statement
The else statement is used in conjunction with the if statement to execute a block of code when the condition evaluates to false.
local exp = 25 if exp > 30 then print("You have leveled up") else print("You are close to leveling up ") end
Elseif statement
The elseif statement allows you to check multiple conditions sequentially after the initial if condition. It provides an alternative condition to check if the initial condition evaluates to false.
local score = 85 if score >= 90 then print("You got an A!") elseif score >= 80 then print("You got a B!") elseif score >= 70 then print("You got a C!") else print("Better luck next time!") end
Relational operators
They are used to compare values and determine the relationship between them. Here are the relational operators in Lua:
- <: Less than
- >: Greater than
- <=: Less than or equal to
- >=: Greater than or equal to
- ==: Equal to
- ~=: Not equal to
Example:
local x = 10 local y = 20 if x < y then print("x is less than y.") end if x == 10 then print("x is equal to 10.") end
Logical operators
There exist three logical operators and,or,not they work this way:
- and: Returns true if all of the current comparations are true, otherwise returns false.
- or: Returns true if at least one of the current comparatios are true, otherwise returns false.
- not: Reverses the logical state of the current comparation.
Example:
local x = 10 local y = 20 if x > 0 and y > 0 then print("Both x and y are positive.") elseif x > 0 or y > 0 then print("At least one of x and y is positive.") else print("Neither x nor y is positive.") end local isRaining = true if not isRaining then print("It's not raining.") else print("It's raining.") end