You may probably heard about If-then-else in programming? Well, It’s like a decision-maker in the code. Basically, it tell your game what to do based on conditions. Let me give you an example: IF a player has enough coins, THEN let them buy the tool with their Robux, ELSE show a error message. Below is the code I created for your reference:
if coins >= toolCost then
-- Deduct coins
player.Coins.Value = coins - toolCost
-- Give the tool
local newTool = tool:Clone()
newTool.Parent = player.Backpack
else
-- Show error message
warn("Not enough coins to buy this tool!")
end
How If-Then-Else work?
In Roblox Lua, simply speaking, if-then-else is a control structure which checks a condition (like the example above) and runs different code depending on whether it’s true or false. It’s super useful in Roblox scripting! Think about if you design a game like “Dead rails“, you would like to make some game rules: “Okay, If you have 199 Roubx, then you can buy some bond; else just ignore it and wait.” See? It’s so common for Roblox game’s shops or object trigger, or leaderboards.
So you can follow below basic coding structure:
if condition then
-- Code runs if condition is true
else
-- Code runs if condition is false
end
Why If-Then-Else is so important for coding?
By using If-then-else, it will surely makes your game more interactive, let me give you few examples:
Controlling Access: Open doors or shops only for certain players (e.g., VIPs). Below is part of the code
if player then
if MarketPlaceService:UserOwnsGamePassAsync(player.UserId, VIP_PASS_ID) then
door.Transparency = 1
door.CanCollide = false
else
player:Kick("This door is only for VIPs!")
end
end
Managing Resources: Check if players have enough coins (like your game’s currency).
if coins >= toolCost then
player.Coins.Value = coins - toolCost
print("Item purchased!")
else
print("Not enough coins!")
end
Customizing Gameplay: Show messages or rewards based on actions.
if score.Value >= 100 then
print("You unlocked a reward!")
else
print("Keep going!")
end
Without if-then-else, your game would be quite boring, players can’t make decisions and surely no fun at all.
Tips for using If-Then-Else
I usually test the conditions by using print() to debug. For example, check the values in each condition so that the logic follow your exceptions. Second, remember to keep it simple, start with one if-then-else before nesting or using elseif. The more complicated it is, the more easy you are getting wrong!
In addition, use clear conditions instead of complex math. For example, coins >= 50 is easy to read. So you must master the basic operators like and, or, ==, ~= in small scripts. If you are not clear, welcome to read my other LUA tutorials for scripting or visit Robox Developer Hub for further references.