-4
echo off
set apk[0]=apk
for /r %%a in (.apk) do call array.bat add apk %%a
call array.bat len apk length
echo apk files found = %length%
for /l %%G in (1,1,%length%) do (
call array.bat getitem apk %%G item
echo %item%
)
echo Pick one:
set /p pick=
call array.bat getitem apk %pick% chose
echo.
echo You picked %chose%.
pause

In the above code i get length of apk array as 9 but the for loop prints ECHO is off 10 times?! I am able to access to individual elements of the array o_O and also down the code after the user picks the choice it displays correctly. What am i doing wrong?

Rico
  • 358
  • 2
  • 11

1 Answers1

3

As a very quick fix, try

call echo %%item%%

This is generation 7,863 of delayedexpansion. There are hundreds of SO entries on this subject. Within a block statement (a parenthesised series of statements), the entire block is parsed and then executed. Any %var% within the block will be replaced by that variable's value at the time the block is parsed - before the block is executed - the same thing applies to a FOR ... DO (block).

Hence, IF (something) else (somethingelse) will be executed using the values of %variables% at the time the IF is encountered.

Two common ways to overcome this are 1) to use setlocal enabledelayedexpansion and use !var! in place of %var% to access the changed value of var or 2) to call a subroutine to perform further processing using the changed values.

Note therefore the use of CALL ECHO %%var%% which displays the changed value of var. CALL ECHO %%errorlevel%% displays, but sadly then RESETS errorlevel.

Note also that your item-displayed using your original code is the last item set in a prior run. You do not have a setlocal command in your batch, so the environment changes are established permanently, not backed out at the end of each batch. The consequence is that you are running with a contaminated environment.

Magoo
  • 77,302
  • 8
  • 62
  • 84
  • setLocal Enabled solved the issue which i didnt actutally understand >.< but i will google it – Rico Sep 29 '14 at 23:43