Ternary Expressions in Luau - Guide (Inline if-statements)

Ternary Expressions in Luau - Guide

Introduction:

As of 2022, the ternary feature has remained an extremely underrated and uncovered feature, that can save lines, and increase readability and elegance in the code.

There isn’t much documentation on it on behalf of Roblox, nor are there any videos and guides covering the updated methods of achieving the ternary operation.

Therefore, in this topic, I’ll be covering the Ternary Expressions of Luau - What are they, their uses, how to write them, and code examples.

(Expressions since they are not Operators, but a method to implement a similar behavior)

Ternary Expressions - what are they?

A ternary operation is like an inline if-statement used to assign values (mostly to variables).
Here’s some pseudo-code (example code, not actual lua)

You could write the if-statement as a single line, directly assigning the value, instead of writing a whole if-statement with the variable outside, to determine the value.

(some pseudo code of what this would look like):

variable = if condition then something else somethingElse

What are they used for?

They can replace whole if-statements with a single, shorter assignment line. Which increases readability, shortens the code, and are more comfortable to line.

If you were to receive a number, you’d have to print whether it’s negative, zero, or positive. How would you go about it?
Most people would use a simple if statement:

local num = -1
if num > 0 then
    print ("positive")
elseif num < 0 then
    print ("negative")
else
    print ("0")
end

Output: negative

However, isn’t that long and unpleasant to read? What if I told you, there’s a way to replace all that if statement, with a single line?
That’s where Ternary expressions come in handy.

Ternary Expressions - writing them:

How does one implement ternary operations?
As of 2022, there are 2 methods of implementing ternary-like operations.

1. if-then-else Expressions

Added in the release of the October Luau recap, and is preferred over the second method, is the if-then-else expression.

When the condition between the if-then is met, the value after the then would be assigned, otherwise, the value after the else will be assigned.

You can add as many elseif-then as you want between the if-then and else- sections.

Let’s take the number code we’ve written before:
Instead of writing a whole if statement, we can now write it in a single line:

local num = -1
print (if num > 0 then "positive" elseif num < 0 then "negative" else "zero") 
--The string printed would be "negative"

If the number is smaller than 0, the value returned would be “positive”, otherwise if the number is smaller than 0, the value returned would be “negative”, lastly if none of the before conditions are met (else), “zero” would be returned.

And the value returned from the expression would be printed.

Let’s do one more example, this time assigned to a variable:
We have 2 scores of players, we need to print which player has more score (assuming an equal score isn’t a possibility):
Using an if statement, it would be long and unpleasant to read:

local score1 = 50
local score2 = 60

local winner
if(score1 > score2) then
    winner = "Player 1"
else
    winner = "Player 2"
end
print(winner)

Output: Player 2
Using the if-then-else expression, we can replace the whole if statement with a single line:

local score1 = 50
local score2 = 60

local winner = if score1 > score2 then "Player 1" else "Player 2" --Player 2
print(winner)

Output: Player 2

As you can see, in both examples we’ve reduced the amount of code into a single if-then-else directly onto the variable (or function in the first example)

2. Truthy expressions using or & and

Before the October recap, this was the way of achieving a ternary-like operation.

In this version, you would write conditions conjoined by and, then conjoin the value you’d like to be returned. or would be used as an elseif or an else

e.g. condition1 and value or elseValue

If we use the examples we’ve used above, the number example would look like this:

local num = -1
print(num > 0 and "positive" or num < 0 and "negative" or "zero")
--Would print negative

The player score one would look like this:

local score1 = 50
local score2 = 60

local winner = score1 > score2 and "Player 1" or "Player 2"
print(winner)
--Would print Player 1

However, this method has multiple disadvantages over the First one:

Disadvantages compared to if-then-else expressions:

  1. It does not support a false or nil success values, and instead overridden by the next or (else)
  2. Can be confused with regular boolean/truthy expressions.
  3. Is less readable overall. When one would read the script, they would not associate and or values as conditional statements.

if-then-else expression is the recommended approach to ternary operations over Truthy expressions.

Source for disadvantages:

Ternary operator for luau

Luau Recap: October 2021

Should I use them over if statements?

It is absolutely your own personal preference for readability. You can use if statements and achieve the same results. Ternary operations do not replace if statements, but they do come in handy in some cases over if statements.

Use what you prefer, and when you find it necessary. In some cases, a ternary operation would not be appropriate.

There are cases in which you shouldn’t:
For example, if you have long/complex if statements with multiple variable assignments and function calls, ternary operations would not be advised, as they’ll make the code less readable.

Personally, I use it mostly when I declare a single variable.

TL;DR:

A ternary operation is like an inline if-statement used to assign values.

Used over if statements in case of simple assignments when an if-statement would be long and unpleasant to read.

In Roblox, there are two methods of implementing them: if-then-else expression, and truthy expression.

  1. local variable = if condition then value else otherValue
  2. local variable = condition and value or otherValue

In general, if-then-else expressions would are better advised due to both readability and false-nil type support for success

To use them or not - it’s personal preference. They sometimes make the code cleaner and more readable, and sometimes not. It really is up to the programmer

They should be used only for simple (and usually single) value assignments, and not instead of complex if-statements that require multiple assignments/function calls and etc.


This tutorial is specifically about Ternary Expressions, which is a conditional statement. To learn more about conditional statements: Luau Conditional Statements and Ternary 101

I hope I’ve managed to teach you what ternary operations are, and how to implement them.
If you find any issues within this guide, please do let me know and I’ll fix them!

Thank you for reading,
Have a great day :sun_behind_large_cloud: /night :new_moon:

25 Likes

I have an opposite opinion about this. Mostly just preference, but I want to give my input.

Sure it shortens the code, but I personally don’t understand how it makes the code more readable.

For me, its just better to format them line-by-line.

I personally think its long and unpleasant to read Ternary expression. It all goes down to preference I guess.

1 Like

It is personal preference and also depends on the usage.

When used appropriately, I find it more readable.

However, that is just my opinion, and my presentation of this option.

One can use whatever they prefer, both work.

Thank you for your input :slightly_smiling_face:

2 Likes

I agree on that one.

The only time I really use Ternary Expressions is for expressions like this:

if not x then return end

Simple statements like that are basically the only time I use Ternary expressions.

3 Likes

Solid tutorial! I commonly use these expressions in my custom chat, but I have yet to switch them over to the new ‘if’ syntax over ‘and/or’.

2 Likes

This is not a ternary, a ternary is like an if, but depending on the condition it will pick some value (sorry if i poorly explained it), this dosent pick any value. this is an example of termary:

print(x and "yes" or "no")

better version:

print(if x then "yes" else "no")

great tutorial.

3 Likes

Well then I personally disliking using ternary expressions.

Ternary expressions are very helpful to development.

Take this for example:

local Open = true

function ShowGUI()
  MyGUI.Visible = Open -- Simple enough, we can use the boolean itself here.
  -- Now let's change some text. Let's assume there's a "Topbar" with "Title" in it that says "Closed" or "Open"
  -- What should we do?
  MyGUI.Topbar.Title.Text = if Open then "Open" else "Closed"
  -- There, we've set it in one line quite easily.
  -- But without ternary you have to do this.
  if Open then
    MyGUI.Topbar.Title.Text = "Open"
  else
    MyGUI.Topbar.Title.Text = "Closed"
  end
  -- Not much point in doing that, and we also added more complexity to our bytecode
  -- since we now have two cases of indexes to MyGUI.Topbar.Title.Text
end

there is an even more simpler version

local function togglevisibility(txtbutton, frame)
   frame.Visible = not frame.Visible
   txtbutton.Text = if frame.Visible then "Close" else "Open"
end
1 Like

I’m not going for barebones functional code. I was writing an example to help someone begin to understand/like ternary operations.

And while, yes, your code works, making it readable and easier to understand is of equal importance when giving a solution/snippet of code.

2 Likes