Using "OR" in variable assignment?

Hey guys,

In a conditional statement I would use or like this

local a = 1

if a==1 or a==2 then
    print("ok")
end

how about when or is used in variable assignment?

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

how does or work in this scenario?

4 Likes

if player.Character returns nil it will run player.CharacterAdded:Wait() and will return the character

5 Likes

It works the same exact way. a or b evaluates to a if a is truthy, b otherwise.

or just basically checks the next conditional statement, if the first one isn’t returned back as true

local Number = 50

if Number == 24 or Number > 25 then
    print("This number is greater than 25!")
end
2 Likes

Great, Thanks. so

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

is equal to something like this?

local player = game.Players.LocalPlayer
local character = player.Character

if character == nil then
    character = player.CharacterAdded:Wait()
end
2 Likes

Conditional statements evaluate based on the last condition that succeeded (or just the last condition if all failed).

print(10 and 30) --> 30 (because 'and' requires all conditions to pass and 30 is the last thing)
print(10 or 30) --> 10 (because 'or' only needs 1 condition to pass, so it stops and thus evaluates 10)

But be careful, because these are not true ternary operations. If you need to capture a false-y statement, these might get you caught up and if statements will work better.

And to your last post: yes, getting the character with both your snippets of code are basically equivalent.

2 Likes

Great, Thank you for the info, I think I’ll stick with if statements.