Below is a variable assignment I found in a script which has made use of the and and or operators.
rightValue = (inputState == Enum.UserInputState.Begin) and -1 or 0
I could not find a simpler example of it being used and so I am really struggling to understand what it does.
Could someone explain to me what the and operator does, and what the or operator does when used in variable assignment?
Thank you to anyone who replies in advance!
and
returns the second argument if the first is true or
reurns the second argument if the first is false.
The and operator has a higher precedence meaning it will be evaluated first which is how this works.
An example of how this is evaluated can be shown by using
print(((true) and true) or false) -- showing evaluation order print(true and true or false)
There are however limitation to this.
print(true and false or true)
You would expect false to be printed but as the operator or returns the second argument if the first is false true will be returned.
There are lots of ways these operators can be used and another example is.
local function foo(tmp) tmp = tmp or 1 -- assigns a default value to the variable tmp if no value is passed end
I hope this helps.
Locked by User#24403 and Amiaa16
This question has been locked to preserve its current state and prevent spam and unwanted comments and answers.
Why was this question closed?