About If statements

I’m sorry if this topic has already been created, I didn’t found the answer to my question so I decided to ask it here.

Is it better to do multiples statements in a single “if” or is it better to insert them in multiples if statements, knowing that the script will work in both options, and why is it better this way? Is it because of the readability of the script, or is it for the performances?

Example of what I mean :

Option 1 :

if 3 < 5 then
    if part.Parent = Torso then
        if part.BrickColor = "Bright Red" then
        print("Hello")
        end
    end
end

Option 2 :

if 3 < 5 and part.Parent = Torso and part.BrickColor = "Bright Red" then
    print("Hello")
end

It completely depends upon you. If you want to do all the checks at once, then you should use one if statement. If you want one statement to be true and then check for the others, you can use multiple if statements.

1 Like

I prefer to do these one liners for readability. Its like efficiency of speech, would you ask two separate questions? Or just one.

You don’t need to worry about the performance of this at all by the way.

2 Likes

I typically just write more if statements when I need more else statements. Performance wise it shouldn’t really make a difference. All depends on personal preference and what checks you are wanting to do.

1 Like

This doesn’t change the results, though the script is a bit harder to read and interpret. Your first option is probably better just so you can read it.

1 Like

Option 2 is better In my Opinion
it’s easier for readability and It’s also less lines and if Option 1 is better then what is the use of “and” and “or”

1 Like

The best way in my opinion is to follow the one on the lua style guide.

https://roblox.github.io/lua-style-guide/#newlines-in-long-expressions

2 Likes

Option 2 is okay for very simple things, such as in your example, but in development you often need to
flesh things out, and when you do, you will often find that there are extra little things that you will need to
insert within the hierarchy, as in your Option 1 example–In other words, often Option 2 will need to be
converted to Option 1 anyway. So with this in mind, always consider the most sensible ordering of tests
which best fit [a conversion to] the Option 1 hierarchical order.

1 Like