Ternary like operation in Lua

Okay, this’ll be a quick one, ternary like operation in Lua.

You think of a ternary operation as a shorthand if-else statement, which is used to take up less space in your codebase.

Consider this code that tells you if a result is greater than 4. Somehow the best example I could come up with.

local result = 0

if result > 4 then
    message = "I am greater than 4!"
else
    message = "I am less than or equal to 4!"
end

print(message)

However this check can be shortened to one line.

local result = 0
local message = result > 4 and "I am greater than 4!" or "I am less than or equal to 4!"

print(message) -->  "I am less than or equal to 4!"

All this is, is some syntactic sugar, so you don’t need to feel obligated to do this.

A more practical example would be this code here, in my “place bomb” effect.

KillerQueen.Bomb.OnClientEvent:Connect(function(stand, placeBomb)
	if placeBomb then
		move(stand, CFrame.new(0,0, -3), info):Play()
	else
		move(stand, summonCFrame, info):Play()
	end
end)

Which yields this result.

The tween is on the client, while the animation is played on the server. Focus on the tween though.

However that code can be shortened to one line.

KillerQueen.Bomb.OnClientEvent:Connect(function(stand, placeBomb)
	move(stand, placeBomb and CFrame.new(0,0, -3) or summonCFrame, info):Play()
end)

It yields the same result, just in a smaller package.

So let me review what you’ve learned.

You can do ternary like operation in Lua by using the logical or, and statements.

You start off with the truthy condition, then you can use the logical or to run a default condition. AKA the “else” part of the code.

You can do if, elseif, and else with ternary operation like this.

local result = 3
local message = result > 4 and "I am greater than 4!" or result == 3 and "I am equal to 3!" or "I am less than 4!"
print(message) --> "I am equal to 3!"

However this can be messy to other scripters, so it’s your choice if you’d like to do it.

I recommend simple if-else conditions, as those are simple and easy to understand but you can do whatever you want.

34 Likes

Been scripting this long and never knew I could really do this. Thanks for that!

2 Likes

Be careful here - if the second operand (after the ‘and’) is falsy (i.e. false or nil) then the entire statement will be evaluated as the third operand (after the ‘or’). You shouldn’t use this as an alternative to proper if statements unless you know the second operand can’t be false or nil.

Example;

local a = true
local b = false
local c = "foo" 
print(a and b or c) --> foo

This is because the ternary operator doesn’t exist in Lua - this is a side effect of how the ‘and’ and ‘or’ operators work.

The ‘and’ is evaluated first, and it’ll evaluate to the right hand expression (b) if the left hand expression (a) is truthy. This means if either a or b are falsy, the entire ‘and’ operation becomes falsy.

After that, the ‘or’ is evaluated. It only evaluates to the right hand side ( c) if the left hand side (a and b) is falsy, hence why it’s returned if b is falsy.

23 Likes

I get away with this using parenthesis and a slightly different expression, though I’m not entirely clued up on the internals of Lua, and whether it’ll yield unexpected results or not - but, at first glance, it seems logical. :smile:

local a = true
local b = false
local c = "foo"

print((a and b) and c) --> false (if b == true -> foo)

Longer expressions may be a bit more convoluted though. :flushed:

1 Like

That’s the same as a and b and c.

5 Likes

Oh yeah, you’re right, haha. I expected that to return truthy/falsy.

Does this has any major or minor effect on performance of script?

I think this is unnecessary knowledge, but its cool to know it. I don’t really think I will end up using it cause I am so used to typing if things like this

CoefficientsLooksGood=true
if CoefficientsLooksGood then
print('👍👍👍')
else
print('you’re just jealous that you don’t have coefficient’s big glasses')
end

Cause it makes sense, if CoefficientsLooksGood is false then I would know that the function in the else would run, if its the other way, then the code in the if will run.
But for the syntax makes a little bit less sense for the shorter if statements.
After if it seems like you use and instead of then then end, then when you use or is almost like using else. It does not make too much sense to me.
Thats just my opinion, thanks for letting me know this. Had know idea this even existed.

I like this operation A LOT. It’s really helpful and it has saved my a ton of time with not having to write excessive if statements. I highly recommend people considering adopting it into your programming. You won’t regret it.

2 Likes

Worth plugging, but, don’t really advise this because it isn’t real ternary. Less lines doesn’t mean more readable. I would take an if statement over fake ternary any day because it makes it explicitly clear what my if statements are doing based on the conditions its given.

9 Likes

From a quick benchmark I can conclude there is no speed difference, all this is, is syntactic sugar. You can choose if you’d like to do ternary like operation or stick to the good ‘ol if statements.

1 Like

When you’re doing this style of coding I recommend to just stick to simple if-else conditions, going beyond with some more complex logic will definitely make it confusing for yourself, and any other scripters reading your code.

That’s correct, but then again, other languages have ternary operation but people usually don’t choose to use it because, well, it can be confusing, you’re same code could be written to this.

local coefficientsLookGood = false
print(coefficientsLookGood and "👍 👍 👍" or "You're just jealous that you don't have coefficients big glasses.")

It’s simply a matter of preference, I choose to do it in simple if-else logic, ternary like operation isn’t meant to replace if statements. They never will.

It can be a kind of syntactic sugar for some people, for others it may not be, but in the end, it’s just your preference.

1 Like

I disagree. I actually find it easier to understand and read because it’s just one line. It’s also easy to explain to programmers reading my code because while the operation is amazingly power, it’s also very easy to understand and use.

2 Likes