Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
4

What does the and operator do in variable assignment? [closed]

Asked by 6 years ago

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!

1
Full explanation under the relevant "and" and "or" sections here: http://lua-users.org/wiki/ExpressionsTutorial  also, the Ternary article (what you're talking about): http://lua-users.org/wiki/TernaryOperator  chess123mate 5873 — 6y
1
If `inputState` is equal to `Begin` then `rightValue `will be -1, else it will be 0 EpicMetatableMoment 1444 — 6y
0
@Chess your link looks broken. Try this http://lua-users.org/wiki/ExpressionsTutorial EpicMetatableMoment 1444 — 6y
0
*(I try to put links at the end of a comment so text after the link doesn't try to interfere with the URL)* EpicMetatableMoment 1444 — 6y

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?

1 answer

Log in to vote
11
Answered by 6 years ago

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.

Ad