Return to Main Page

If, then, else

Page white text.png Description:This is an introduction to the lua language in general and is a recommended read if you are a beginner.
link=User:Dim1xs Author:Dim1xs
Calendar.png Created:September 29-30th 2023

If statements

The first thing I want to teach you is the "if" statement. This statement is a very basic, direct order to lua. This can be really useful in creating your own scripts. "If" tells the code to do something if a condition is true or not. This is a simple if statement:

local Int = 5

if Int == 3 then
   print( "Int is 3")
end
               
Or in such variants:

local isTrue = false

if isTrue == false then
   print("False")
end
               
Condition has to be false to run the code block after it. A code block is code that only runs under certain conditions. In this case, the code block runs if the condition is false.

Else statements

Else is used to define the opposite of the condition, so if a condition is true, then else would tell it to execute the following code, a good usage of else is shown below.
local Int = 5

if Int == 3 then
   print( "Int is 3")
else
   print( "Int is NOT 3")
end
               
The above example checks if the variable "Int" is 3, if this is true, then it prints to console "Int is 3", but if the variable "Int" is NOT 3, then it prints "Int is NOT 3" to console.

Conditions Available For Use

Equal To

The equal to condition is true if the thing on the left and right of == are equal.

local Int = 5

if Int == 3 then
   print( "Int is 3")
end
               

Not Equal To

The "not equal to" condition is true if the thing on the left and right of ~= aren't equal. You can also use != instead of ~=

local Int = 5

if Int ~= 3 then
   print( "Int is NOT 3")
end
               

Less Than

The "less than" condition is true if the thing on the left is less than the thing on the right.

local Int = 5

if Int < 3 then
   print( "Int is less than 3")
end
               

Greater Than

The "greater than" condition is true if the thing on the left is more than the thing on the right.

local Int = 5

if Int > 3 then
   print( "Int is greater than 3")
end
               

Less Than or Equal To

local Int = 5

if Int <= 3 then
   print( "Int is less than 3 or below")
end
               

Greater Than or Equal To

local Int = 5

if Int >= 3 then
   print( "Int is greater than 3 or over")
end
               

Thank you for reading this tutorial, see ya later!

JOIN HL2GMED DISCORD SERVER!