How to check if an index exists in an array?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Zero
:warning: Old Version Published before Godot 3 was released.

Basically what I want to do is:

if (array[i] index exists):
  do something
else:
  do something else

Can anyone help please? Thank you for reading.

:bust_in_silhouette: Reply From: kidscancode

Arrays are ordered, so an array will always contain indices from 0 to array.size() - 1

:bust_in_silhouette: Reply From: Awxen

If you want to check if an array has a certain index or not;

var array = []
var index: int

if range(array.size()).has(index):
  print()

index can be any number of your choosing and the statement will return a bool based on whether the array has the index or not.

You can also replace ‘index’ with the iterator variable if the above statement is inside a for loop. It would need to be done this way:

for i in range(array.size()):
  if range(array.size()).has(i):
    print()
:bust_in_silhouette: Reply From: DarkShroom

faster code would be to check the bounds:

static func array_has_index(array : Array, index : int) -> bool:
    return index >= 0 and index < array.size()