Lua 1.1
Lua 1.1
In Lua, conditions are used to control the flow of execution based on specific
criteria. Here's a simplified guide to all possible conditional structures in Lua:
1. If Statement
The basic if statement checks whether a condition is true or false and executes
code accordingly.
if condition then
-- code to execute if condition is true
end
Example:
local age = 20
if age >= 18 then
print("You are an adult.")
end
2. If-Else Statement
The else clause allows you to specify code to execute when the if condition is false.
if condition then
-- code if condition is true
else
-- code if condition is false
end
Example:
local age = 16
if age >= 18 then
print("You are an adult.")
else
print("You are a minor.")
end
3. If-Elif-Else (elseif) Statement
You can check multiple conditions using elseif.
if condition1 then
-- code if condition1 is true
elseif condition2 then
-- code if condition2 is true
else
-- code if neither condition1 nor condition2 are true
end
Example:
local age = 25
if age < 18 then
print("You are a minor.")
elseif age >= 18 and age < 60 then
print("You are an adult.")
else
print("You are a senior citizen.")
end
4. Logical Operators
You can combine multiple conditions using logical operators:
and: True if both conditions are true.
or: True if at least one condition is true.
not: Reverses the truth value.
if condition1 and condition2 then
-- code if both conditions are true
end