Note: This is the basics and probably does not cover everything about the if statement - This is intended for beginners wanting to learn lua.
Basic If Statement
The if statement is useful when you want to compare data, strings, integers and other types of data can be compared
First, lets see a syntax template
if --[[COMPARISON]] then
--CODE IF COMPARISON IS TRUE
end
Let's see some basic code to understand it easier
if 2 + 2 == 4 then
print("yay")
end
Output:
yay
Basically, if 2 + 2 is 4 (which it is) then write yay on the screen
The comparison is slotted between the words "if" and "then" (See where it says 2 + 2 == 4)
To check if something IS THE SAME AS something else, use a double equals sign (==)
If we change the code to something incorrect…
if 2 + 2 == 5 then
print("yay")
end
Output:
… It dosen't say anything. Because 2 + 2 is not 5 then it skips over the entire if statement.Some comparison signs you can use:
a == b See if a is the same as b
a > b See is a is bigger than b
a < b See if a is smaller than b
There are more, but these are the basic onesIf…Else Statement
Another kind of if statement is the if…else statement.
if --[[COMPARISON]] then
--CODE IF COMPARISON IS TRUE
else
--CODE IF COMPARISON IS FALSE
end
Some easy to understand code
if 2 + 2 == 4 then
print("yay")
else
print("nay")
end
Output:
yay
Because 2 + 2 is 4 then it says yay and skips over the code in the else part but if we change the code to so something incorrect…
if 2 + 2 == 5 then
print("yay")
else
print("nay")
end
Output:
nay
… It says nay. Because 2 + 2 is not 5 then it skips over the main if code and executes the code in the else partNot Modifyer
Lets come back to this code
If we want this code to output "yay", we can change the expression toOutput:if 2 + 2 == 5 then print("yay") end
… It dosen't say anything. Because 2 + 2 is not 5 then it skips over the entire if statement.
not (2 + 2 == 5)
Notice how I use brackets - the not modifier does not (no pun intended) always play well with mathThe code would be
if not (2 + 2 == 5) then
print("yay")
end
Output:
yay
Using the word "not" before typing the expression makes it say yay. 2 + 2 is not 5 so it is false. The "not" word makes false expressions true, therefore running the code. It also makes true expressions false, therefore skipping over the code.Strings and Variables
If statements can use variables and strings so this code would not error
a = "Hi"
if a == "Hi" then
print("yay")
else
print("nay")
end
Output:
yay