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

What does the and operator do in variable assignment?

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!

4 comments

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 

1

If inputState is equal to Begin then rightValue will be -1, else it will be 0

0

@Chess your link looks broken. Try this http://lua-users.org/wiki/ExpressionsTutorial

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)

1 answer

✓ Accepted answer

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.

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