OR Operator executes code multiple times!

I have a question regarding the OR operator in the following script:

char.Humanoid.Touched:Connect(function(hit)
	if hit.Name == "Wall1"
		or hit.Name == "Wall2"
		or hit.Name == "Wall3"
		and debounce == false then
		debounce = true
		part1.Sound:Play()
        wait(0.5)
        debounce = false
	end
end)

When I touch Wall1 the play function is executed three times, when I touch Wall2 it is executed twice and when I touch Wall3 it is executed only once. Why is this?
Because OR should evaluate a true if one condition is true and execute the code! And i do not touch all the different walls at the same time!

1 Like

It’s not running the code like you think it is. Try placing parenthesis around your or statements.

char.Humanoid.Touched:Connect(function(hit)
	if (hit.Name == "Wall1" or hit.Name == "Wall2" or hit.Name == "Wall3") and not debounce then
		debounce = true
		part1.Sound:Play()
        wait(0.5)
        debounce = false
	end
end)
2 Likes

Ok that works, thanks!
But I still don’t understand why the code is executed three times without brackets when I touch Wall1 only. Maybe someone can explain this.

The and-operator is evaluated before the or-operator similar to how in math you multiply/divide before you add/subtract.
That’s why your debounce only works with wall3 and you need to parenthesis in place.

1 Like

This is not even mentioned on the Roblox Developer page! The Lua Reference says the following about it:

Operators Precedence in Lua

Here, operators with the highest precedence appear at the top of the table, those with the lowest appear at the bottom. Within an expression, higher precedence operators will be evaluated first.

Category Operator Associativity
Unary not # - Right to left
Concatenation Right to left
Multiplicative * / % Left to right
Additive + - Left to right
Relational < > <= >= == ~= Left to right
Equality == ~= Left to right
Logical AND and Left to right
Logical OR or Left to right

Create a post in #bug-reports:developer-hub asking for the table to be added to Operators and/or Conditional Statements pages.

2 Likes