Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
1

Question about conditionals?

Asked by
Kishero 10
8 years ago

Hello there, I am new to ROBLOX and it's community, and as I jump in, I'd like to learn how to program in rbx.lua. So I've been studying scripting and it all seems pretty simple, but to make sure that I understand what I've learned so far, I wanted to ask the community.

My question is about conditionals, from what I've read, they only run the enclosed code if the pareneter returns true?

Would

if true then
 print("Test")
end

Output "Test"

And

if false then
 print ("Test")
end

Not output anything?

Thanks!

2 answers

Log in to vote
1
Answered by
Perci1 4988 Trusted Moderation Voter Community Moderator
8 years ago

You're totally right (although they're technically not called parameters). The if statement will run if (and only if) its condition is true.

Obejcts, numbers, and strings are considered true. nil is considered false.

We can use keywords like or and and to manipulate this behavior a bit.

if true or false then

If you read this in English, it should make sense. This if statement will run its code if true is true, OR if false is true. Since true is true, it will run.


if true and false then

Again, this makes sense if you read it in English. This if statement will run its code if true is true, AND if false is true. Since false isn't true, it won't run.


Both these words can be mixed up, but this can be a bit confusing. and has a higher precedence than or. Personally, I think it's safest and cleanest to use parentheses for the correct order.

if false or (false and true) then

This code will run in two possible situations (because we used or). It will run if false is true, OR if false and true are both true. Since neither of these situations work, it won't run.


Both keywords will "short-circuit", that is, the second or finds a single true condition, no other condition will be checked.

if print(5) or true then
if true or print(5) then

Both these statements will run, but only the first condition will be checked. Run these for yourself and look at the output.

and works the same way, except it will stop running at the first value that equals false. This lets us do things like

if humanoid and humanoid.Health > 0 then

without fearing an error, because if the humanoid doesn't exist its health will never be checked.

Comment with questions!

Ad
Log in to vote
0
Answered by
1waffle1 2908 Trusted Badge of Merit Moderation Voter Community Moderator
8 years ago

Yes. More specifically, an object can be used, and nil is also interpreted as false if the object does not exist, so if workspace:FindFirstChild("BasePlate")then is valid.

Answer this question