how to check if a variable is equal to a least one variable in an array

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By adopted_child

I have a signal that sends a int. If the int is the same as one of the ints in an array i want to run some code.

How do I check/compare the int to an array?

(this is in GDscript btw)

:bust_in_silhouette: Reply From: jgodfrey

Edit: While the custom iteration method shown here will work, see my update in the comment for something simpler.

You’ll need to iterate through the array and check each value. A simple function will make this easier. Something like:

func ready():
    var arr1 = [1, 5, 12, 16]
    print(">> %s" % array_contains(12, arr1))
    print(">> %s" % array_contains(10, arr1))

func array_contains(val, arr):
	for item in arr:
		if item == val: return true
	return false


>> True
>> False

Err… Wait… Forgot that GDScript’s Array object supports a has method. So, just this should work:

var arr1 = [1, 5, 12, 16]
print(">> %s" % arr1.has(12))
print(">> %s" % arr1.has(10))

jgodfrey | 2022-11-17 19:16