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!
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!
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.