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?
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
Locked by User#24403
This question has been locked to preserve its current state and prevent spam and unwanted comments and answers.
Why was this question closed?