Still have questions? Join our Discord server and get real time help.
Log in to vote

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

Asked by 3 months 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!

Full explanation under the relevant "and" and "or" sections here:  also, the Ternary article (what you're talking about):  chess123mate 4260 — 3mo
If `inputState` is equal to `Begin` then `rightValue `will be -1, else it will be 0 SinisterMemories 653 — 3mo
@Chess your link looks broken. Try this SinisterMemories 653 — 3mo
*(I try to put links at the end of a comment so text after the link doesn't try to interfere with the URL)* SinisterMemories 653 — 3mo

Locked by incapaxx and Kiriot22

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
Answered by
kingdom5 5269 Trusted Snack Break Moderation Voter Community Moderator
3 months 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

I hope this helps.