Having 'or' in variables

I have seen many people put or in their variables like so:

local colour = 'Blue' or 'Red'

What does it mean to have or in variables?

3 Likes

or always works the same. a or b evaluates to a if a is truthy, b otherwise.

So colour gets the string "Blue"

4 Likes

Usually they’re used as backup variables.

like in your case, red is a backup variable just in case blue doesn’t exist.

1 Like

It is a conditional statement. If 'Blue' is unequal to nil or false, it evaluates as itself since 'Blue' is a string (strings are unequal to nil and false).

Though, your example is definitely not realistic as everyone knows 'Blue' exists and a better representation is an unpredictable variable as 'Blue'. (what I mean by “exists” is that it is not nil or false.)

If you want to learn more, this could help you.

3 Likes

Let’s elaborate on that, or basically is the short form of this:

local colour = "Blue"
if not colour then
    colour = "Red"
end

Like @sjr04 said, if one doesn’t exist, it will use the other one. Let’s take this for an example:

local Character = Player.Character or Player.ChracterAdded:Wait()

If the character isn’t there(hasn’t loaded in yet), the Player.ChracterAdded:Wait() will run, and if Player.Character already exists then Player.ChracterAdded:Wait() won’t run.

4 Likes

In local scripts, I have seen them get the character like this:

local character = player.Character or player.CharacterAdded:Wait()

does this mean if player.Character can’t be found it just waits for the character to be added? But that doesn’t get the character does it? It just waits for the character. Sorry if this didn’t make sense.

2 Likes

If player.Character evaluates to nil then the second operand is evaluated. Since event:Wait returns what would have been the arguments to its listeners then it will yield the thread and return the character

2 Likes

player.CharacterAdded:Wait() does return the character once it’s added, yes. You can see what event:Wait() will return by looking at the parameters of the event on the wiki:

3 Likes

I call that an inline expression, which is very efficient.

What you can do:

local Var -- nil
print(not Var and 'var is nil' or 'var is ' .. Var)

This will print var is nil.
If you assign anything (other than false or nil), it will print var is <anything>, ex: 1.

1 Like