"x and y or z" or "if x then y else z end"?

What do you want to achieve?

I read somewhere about a quirky way to assign a variable based on a condition. It goes like this:

local object = condition and this or otherwise

It is another way of writing this:

local object
if condition then
	x = this
else
	x = otherwise
end

What is the issue?

I am unsure if the and-or method is more efficient than if-else. Other than being faster to write on the fly, does it actually work faster to do the former than the latter?

What solutions have you tried so far?

I searched the Developer Forums for similar questions, and it seems that there are no results for similar questions to what I’m asking. I also do not know how to calculate the speed of either.

1 Like

I don’t believe there’s any major speed difference, but I think you should use if-then-else instead of and-or.

Edit: Roblox recently introduced if-then-else, a proper ternary operator as a sort of replacement for and-or. I don’t think there’s big a difference between this and if CONDITION then SOMETHING else SOMETHING end

local x = a and 2 or 3

local x = if a then 2 else 3

It makes more sense grammatically. Also, you can do;

local x = if a and y then 2 else 3

Which with and-or it’s

local x = a and y and 2 or 3

Which looks really weird.

1 Like

There is barely any difference in performance between the two. However, using the x = if then else only has two conditions, where the x = a and A or b and B or c and C can have as much as you want. It still depends on what you want. If you prefer readability, then use the if-else, while and-or if you want minimal typing.

2 Likes

Thanks! As for the multiple conditions thing, I could parenthesize the conditions, and make it look like this:

local x = (a and A or b) and B or c

Also, TIL that ROBLOX did add writing an if-else as a variable designation.

You’re actually looking for two different use cases of both. The former is applicable whenever the execution is simple and the latter for more complicated logic. Note that the former reduces traceability but does not change the semantics.

1 Like