Menu
CoddyTech

any and all

Part of the Logic & Flow section of Coddy's GDScript journey. Lesson 63 of 78.

any() and all() ask a yes-or-no question about a whole array. Both take a function that returns true or false for one element:

  • any() returns true if the function returns true for at least one element.
  • all() returns true if the function returns true for every element.
var enemy_hp = [30, 0, 12]
print(enemy_hp.any(func(hp): return hp == 0))
print(enemy_hp.all(func(hp): return hp > 0))
true
false

One enemy has 0 HP, so any() is true, and that same enemy makes all() false.

Both stop as soon as the answer is known: any() at the first true, all() at the first false. They work with named functions too, like numbers.all(is_even).

On an empty array, any() returns false, because no element passes, and all() returns true, because no element fails.

Use them in a condition in place of a loop with a flag variable:

var inventory = ["sword", "key", "rope"]
if inventory.any(func(item): return item == "key"):
	print("The door opens")
challenge icon

Challenge

Easy

The program reads one line of scores separated by commas and stores them in the array numbers. This part is already written.

Print two lines:

  1. Any perfect: followed by true if at least one score is 100, otherwise false
  2. All passed: followed by true if every score is 50 or more, otherwise false

Use any() for the first line and all() for the second. For the input 100,75,40, the output is:

Any perfect: true
All passed: false

Try it yourself

extends Node

func _ready():
	var numbers := []
	for part in OS.read_string_from_stdin().split(","):
		numbers.append(int(part))
	# Print the two lines with any() and all()
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow

Practice on your own: Online GDScript compiler