Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

What does OR do when defining a variable?

local TestA = "Hello"
local TestB = nil

local Variable = TestA or TestB
print(Variable)

I haven't tested this out yet, but I'm assuming that what will be printed is "Hello" as TestB is nil? May someone clarify this for me? What if TestA and TestB are both NOT nil? What will be printed?

2 comments

1

It's basically an alternate operator , if something doesn't equal to this, or if unavailable, or, if alternate defined, will pass the alternate as a second option

1

Example: local character = player.Character or player.CharacterAdded:wait() if 'player' doesn't exist, it'll use the alternate method provided, which was to wait for the CharacterAdded event, instead of setting the variable to nil

2 answers

✓ Accepted answer

or is an operator; to be more specific, it is a logical operator. Before I explain to you the specifics, keep in mind that, like control structures, logical operators treat false and nil as falsey and anything else as truthy. Here are all the logical operators:

  • exp1 or exp2 evaluates to exp1 if it is truthy; otherwise, it evaluates to exp2.
  • exp1 and exp2 evaluates to exp1 if it is falsey; otherwise, it evaluates to exp2.
  • not exp evaluates to true if exp is falsey or false if exp is truthy.

With this in mind, consider the following code:

print(nil or "hello") --> hello
print(false or nil) --> nil
print(true or false) --> true

print(nil and "hello") --> nil
print("hello" and false) --> false
print(true and false) --> false

print(not true) --> false
print(not nil) --> true
print(not 123) --> false

Regarding your code and question, "Hello" or nil would indeed evaluate to "Hello". "Hello" or true would also evaluate to "Hello".

or compares two values. In your code snippet, the operator will determine which value is not nil and return that, therefore printing Hello. If neither values are truthy, or will return false. Note that if both values are truthy, the first value will be returned. Contrastingly, the and operator will return the last given value is all are truthy.

local a = 1
local b = false

print(a or b) --> a

---------------

local a = "hi"
local b = "there"
print(a or b) -> "hi"

---------------

local a = false
local b = false
print(a or b) -->false

---------------

local a = true
local b = 2
local c = "hi"

print(a and b and c) --> hi

or

1 comment

0

"If neither values are truthy, or will return false." is incorrect. "the and operator will return the last given value is all are truthy." is also incorrect; see my answer for an explanation :)

This discussion is preserved as it was. New answers, comments, and votes are closed.