"Or" conjunction not working?

Godot Version

Godot 4.4

Question

I’m trying to use an “if” statement with “or” conjunctions to call lines of an array. However, when I print text with these conditions, the print statements overlap. When I separate each “or” into a different “if” statement, the code works fine.

Here is the code I am using:

func _on_button_pressed() -> void:
	var entry = TEXTS.instantiate()
	dialogue_entries.add_child(entry)
	
	if _next_content_index >= CONTENTS.size():
		print("The last line has already been added!")
		return
	if _next_content_index >= SPEAKERS.size():
		print("The last line speaker has already spoken")
		return
	if _next_content_index == 2 or 3 or 5 or 9:
		print("Speaker 2 Speaks")
		entry.anchor_left = 200
	if _next_content_index == 1 or 4 or 6 or 7 or 8:
		print("Speaker 1 Speaks")
		entry.anchor_left = 0
	entry.set_content(SPEAKERS[_next_content_index], CONTENTS[_next_content_index])
	_next_content_index += 1

Here is what the console looks like:

Any non-zero integer will always evaluate to true when used as an operand for logical operations. Doing:

if _next_content_index == 2 or 3 or 5 or 9

is same as doing:

if _next_content_index == 2 or true or true or true

So those two of your ifs will always be true.

To make this work properly, you’ll need an == test for each number. That may be a bit too long and repetitive, but there are alternatives. You can put those numbers into an array and use in operator to test if a value is in that array:

if _next_content_index in [2, 3, 5, 9]:
	# stuff

Other option is to use match:

match _next_content_index:
	2, 3, 5, 9:
		# stuff
	1, 4, 6, 7, 8:
		# other stuff
2 Likes

That worked for me, thank you!

1 Like