October 21, 2014 at 2:36 AM

Beginner Lua Lesson 5: “if” statements & “end” explained

Previous Lua Lesson

First Lua Lesson

If you’ve read other scripts to practice your skills, you’ll very commonly see in bold, blue letters the words “if” and “end.” But what exactly do these mean?

if

“if” is used to check the parameters of a certain value, whether it be a string, object, or number. You can use it to check nearly everything. After “if,” you write what value you wish to check. Then, you will use == to see if that value matches with another value, which comes after the “==.” As well, you can do the opposite: check if two values do not match, by instead typing “~=”. After that, you must write “then”. The following code that comes after then is what’s executed if the two values do (not) match. If the two values do (not) match, the boolean returned into the if statement is “true.” This means that the if statement will go through its following code if true is thrown into there. Essentially, this means you could do this in a script: if true then

elseif

In case the previous if statement returns false, you can check something else’s value(s) in the same block of code without executing another function.

else

If all previous if statements (including elseif) in the same block of code fail, you can execute different code to correspond with that without checking more value(s).

Example

local calculation = 2 + 2

if calculation == 5 then
print("2 + 2 = 5!")
elseif calculation == 3 then
print("2 + 2 = 3!")
else print("2 + 2 = 4!")
end

Extensive usage of if statements

There are two more parameters you can add in an if statement: “and” and “or”. These do just as they sound like: They can check for more value(s) in the same if statement; whether it being a different way to execute the same code (or), or executing code from two or more value checks (and). These can both be called many times in the same if statement, but they do not mix. If you wish to mix them together in the same if statement, you must use parenthesis to separate them. You do not have to add another if and then in the parenthesis.

As well, if you’re just checking if a boolean is not false or nil, you do not need to add “==”/”~=”. Just place the value to check within the if statement. If you wish to check vice versa the same way, change “if” to “if not”. This can also be a replacement to “~=”, but you would still have to use “==” with the not.

Finally, if you’re doing math in scripts, you can do algebraic things like greater than and less than. Here is what you would replace with “==”/”~=” in that case:

Greater than: >

Greater than or equal to: >=

Less than:

Trending