Ternary Operator

Guys I forgot how to do it what is the ternary operator for saying " If this is true then do this else do this" but you can use it with something like “true and 0 or 5” or something?

I have this Body Velocity function and I just wanna know how the operator works so I can basically say instead of 3.5 I want to say if Combo < 4 then It’s 3.5 otherwise It’s 45, thanks.

local BodyVelocity = Library.Functions.BodyVelocity(EnemyCharacter.HumanoidRootPart,Player.Character.HumanoidRootPart.CFrame.LookVector * 3.5,Vector3.new(100000,0,100000),0.1)

Before Someone responds with “well you can just do if combo <4 then variable = 3.5 else variable = 45 end” I know I can do that clearly but I want to know how the operator works since this is a commonly needed thing.

local a = x and y or z

if x is truthy, the value will be y, else z

Updating old post:
Luau now supports built in ternary! local a = if x then y else z is the syntax. Learn why and more here:

2 Likes

so I can put something like

HumanoidRootPart.CFrame.LookVector * combo < 4 and 3.5 or 45

Should work, but look vector is a vector, so checking if it’s less than will probably throw an error along the lines of attempt to compare Vector3 < number

I think this is what you want:

HumanoidRootPart.CFrame.LookVector * (combo < 4 and 3.5 or 45)

wait so putting parenthesis will stop it from throwing a error? Do parenthesis in lua when doing equations and suff ensure it runs what inside and gets the result before comparing code like the vector 3 and result of the ternary operator?

Parentheses change the order of execution. So (combo < 4 and 3.5 or 45) will be resolved and then the result multiplied to the vector.

oh didn’t know that thankyou so that should stop it from erroring when I test it thanks.

One thing to note is that due to the logic of the short circuit evaluation, the second expression (right after the and) can not be nil or false for it to work properly, or it will always go to the third one. But an easy fix is to just negate the first expression

Good note, but it would just be easier to use if-then-else expressions as they get rid of this problem instead of using and-or as shown in the post up above