0 votes

If I have a array of nodes like this

var items = [obj01, obj02, obj03]

I like to know if there is a way to perform a for loop of items but skip obj02 by using the index number.

for example, if I put

if i == 2: 
  continue

the 2 is only recognised by value not the index order in the array, not sure if continue could work with index order instead of value. Thank you.

Godot version v3.2.3
in Engine by (248 points)

2 Answers

0 votes
Best answer

A couple different approaches.

# skip if i is 2
var items = [obj01, obj02, obj03]
for i in range(len(items)):
  if i == 2:
    continue
  else:
    do_thing(items[i])

Or:

# shift i one over at the right time
var items = [obj01, obj02, obj03]
for i in range(len(items) - 1):
  if i >= 2:
    i += 1
  do_thing(items[i])

Or even:

# make a "for loop" using a while loop
var items = [obj01, obj02, obj03]
var i = 0
while i < len(items):
  do_thing(items[i])
  if i == 1:
    i = 3
  else:
    i += 1
by (83 points)
selected by

Thank you for your help.

+1 vote

Hacky way:

var index = 0:
for n in array:
   if index != 2:
      pass #do something, if index is 2 skip it
   index+=1

or traditional while loop:

var index = 0
while(index<array.size()):
   if index !=2:
      pass #do something if index is 2 skip it
   index += 1
by (334 points)
Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to webmaster@godotengine.org with your username.