Page 1 of 1

How to return the index of an array in a for loop?

Posted: Thu Sep 06, 2018 11:58 am
by henvu50

Code: Select all

for item in arrayTest:
  # what index array number are we on ?
  text arrayTest.index(item) + "\n" 
How do I get the index number the loop is on? When it loops, I should have access to a number that represents what count the loop is on, how do I access the loop count number?

Re: How to return the index of an array in a for loop?

Posted: Thu Sep 06, 2018 12:06 pm
by rames44
Well, one way is

Code: Select all

i = 0
for item in arrayTest:
    (Use i as the index)
    i += 1

Re: How to return the index of an array in a for code]oop?

Posted: Thu Sep 06, 2018 12:11 pm
by MaydohMaydoh
What you want is range and len

Code: Select all

for i in range(len(arrayTest)):
    text arrayTest[i]

Re: How to return the index of an array in a for loop?

Posted: Thu Sep 06, 2018 12:19 pm
by henvu50
Thanks, I changed my code accordingly.

Is it safe to use $ in a vbox for a loop? Doesn't $ make the variable global? If I use $ index somewhere else couldn't it conflict?

Code: Select all

    vbox:
        $ index = 10
        for item in reversed(arrayTest):
            text "[index]" 
            $ index -= 1 

Re: How to return the index of an array in a for loop?

Posted: Thu Sep 06, 2018 4:12 pm
by Remix
or...

Code: Select all

for idx, item in enumerate( arrayTest ):
    text "[idx] : [item]"

Re: How to return the index of an array in a for loop?

Posted: Thu Sep 06, 2018 5:17 pm
by trooper6
$ doesn’t make a variable global. $ is used to indicate the line is a line of python code and not RenPy code.