Scripting Lesson 005: If-Then Statements

Hello there! Welcome back to scripting lessons. Now this lesson will be a longer one in which we will discuss if-then statements, one of the most important subjects in both beginning and advanced scripting. If-then (also else) statements are basically when a script does either one action or another based on the condition it is identifying. For example, let's go to one of my game projects with PurpleDev Studios: City of Bloximore.

In this script, I have once again labeled what is going on. This is a script for job assigning (ignore all the GetPlayerFromCharacter, and Values and stuff, just focus on the main picture).

Now first, let's look at line 4 a little better. An if-then statement always starts with...well....if. Then you put in a certain criteria with 'and' in between each one. Afterwards you end the line with then. Basically the script line translated into English is: If the XP Value of the Player is greater than 0, the playerstats are existent, and the workspace is existent then perform the next task. If the criteria is met, the ScreenGui changes but if it doesn't, the script cancels out, leaving no change (unless of course you add something before the if-then statement like changing the transparency of the Gui or something).

Now of course it is also important to remember that if-then statements always need an end to close them off, meaning you need two ends at the end of this script. When you get into more advanced scripting this becomes more common.

Now we move onto something else, if-then-else statements. You already saw the script from before, but let's look at the main job script in Bloximore. This script is a little more advanced but what it does is it takes the text in your gui and uses it to give you a certain amount of money every 2 seconds. If this is too much to follow along to, just focus on line 1-5 and the ends.

Now this is a little different than what you were expecting. This contains elseif statements, not else statements. What is the difference? Else statements continue if-then statements by saying "If this criteria ISN'T met, then this happens" and is simple else followed by the rest of the action. A better example has been made here:

Now as you may have noticed, the equal signs are double in the if-then statement of this script. That is mandatory for any if-then statement. It will not work otherwise. So now I have made an elseif version of this

So this is extremely helpful when developing games, especially with things like group-only doors and other scripts that narrow the action to only few players or situations. To help better understand these statements. PM me on Roblox.com or practice with Exercises below.

Exercise- Make a brick that if clicked by you, does nothing, but if clicked by another person, kills them

Challenge- Make an onTouched script that kills you if a certain player is in the game (You touch the brick, then statement begins)

-Domswolf