Subham Tripathi
Subham Tripathi

Reputation: 2733

indexing in array in for loop [wrong output] [batch]

I am trying to loop through an array by step size of 2. what i want is to take 2 values in one iteration and then process it (i.e say i and i+1 index needs to processed in everyloop). for that i wrote following snippet.

for /l %%a  in (1,2,!counter!) do (
    set username=!array[%%a]!
    set /a nextindex=%%a+1
    echo username:!username! index: !nextindex! value [!array[%nextindex%]!]
)

when i run this piece of code, the output that i get is :

username:FT_SelfAdmin01 index: 2 value []
username:FT_SelfAdmin01 index: 4 value []
username:FT_SelfAdmin01 index: 6 value []

when i ran the above batch in echo on mode i get following

(
set username=!array[1]!  
 set /a nextindex=1+1  
 echo username:!username! index: !nextindex! value [!array[nextindex]!] 
)

when i change this line

echo username:!username! index: !nextindex! value [!array[%nextindex%]!]

to this line
echo username:!username! index: !nextindex! value [!array[!nextindex!]!]

i get this (as echo of code)

echo username:!username! index: !nextindex! value [!array[!nextindex!]!]

and output changes to (i am giving only one line here)

username:FT_SelfAdmin01 index: 4 value [nextindex]

i am not able to understand what is happening ?

Upvotes: 0

Views: 92

Answers (2)

MC ND
MC ND

Reputation: 70923

Original line

echo username:!username! index: !nextindex! value [!array[%nextindex%]!]

This will not work as the %nextindex% variable reference, not using delayed expansion, was replaced when the full for %%a block was parsed.

Changed line, now with delayed expansion

echo username:!username! index: !nextindex! value [!array[!nextindex!]!]
              ^........^        ^.........^        ^......^         ^.^

The variables the parser sees are not what you think. It is not possible to use delayed expansion inside delayed expansion.

How to solve? for replaceable parameters

for %%b in (!nextindex!) do (
    echo username:!username! index: !nextindex! value [!array[%%b]!]
)

Upvotes: 2

martin
martin

Reputation: 2638

If I understand your question right (and that's kinda hard to say), something like this should help you:

@echo off

rem Just init the array
setlocal EnableDelayedExpansion
set n=0
for %%a in (A B C D E F) do (
  set array[!n!]=%%a
  set /A n+=1
)

for /L %%c  in (0,2,5) do (
   set username=!array[%%c]!
   set /a nextindex=%%c+1
   call set val=%%array[!nextindex!]%%
   echo username:!username! index: !nextindex! value [!val!]
)

the output of this is:

username:A index: 1 value [B]
username:C index: 3 value [D]
username:E index: 5 value [F]

Upvotes: 0

Related Questions