Excallypurr
Excallypurr

Reputation: 319

Why won't my for loop using random work in batch?

@echo off
goto :food
SETLOCAL EnableDelayedExpansion
for /F "tokens=1,2 delims=#" %%a in ('"prompt #$H#$E# & echo on & for %%b in (1) do     rem"') do (
  set "DEL=%%a"
)

:fruits
set i=0
for %%a in (apple banana grape lime) do (
   set /A i+=1
   set fruit[!i!]=%%a
)
set /a fruit=%random%%%4+1
set fruit=!fruit[%fruit%]!
exit /B

:food
for /l %%x in (1, 1, 5) do (
call :fruits
call :colorEcho 70 !fruit!
echo/
)
pause

exit
:colorEcho
echo off
<nul set /p ".=%DEL%" > "%~2"
findstr /v /a:%1 /R "^$" "%~2" nul
del "%~2" > nul 2>&1i

For some reason that I don't know, this code does not output correctly. It outputs just blank spaces because for some reason the "fruit" variable is never being filled. Can anyone explain this to me? I have another script which works fine using a similar structure but extracting these parts out of that script totally breaks it...any help is much appreciated!

Upvotes: 0

Views: 130

Answers (2)

Aacini
Aacini

Reputation: 67226

You have the right code in the accepted answer at your previous question. The "some reason" because your code does not work is the modifications you introduced in such a code, so you just need to duplicate the same scheme...

There are multiple ways to achieve the same thing. I always prefer the simplest one; for example:

@echo off
setlocal EnableDelayedExpansion

for /F %%a in ('echo prompt $H ^| cmd') do set "BS=%%a"

:food
for /l %%x in (1, 1, 5) do (
   call :fruits
   call :colorEcho 70 !fruit!
   echo/
)
pause
goto :EOF


:fruits
set /A i=%random%%%4+1
for /F "tokens=%i%" %%a in ("apple banana grape lime") do set fruit=%%a
exit /B

:colorEcho color text
set /P "=%BS% " > "%~2" <nul
findstr /A:%1 "^" "%~2" nul
del "%~2"
exit /B

Upvotes: 2

Squashman
Squashman

Reputation: 14320

You have to make the backspace first. The colorecho function requires that variable be defined. You are skipping over it because the second line of your code does a GOTO FOOD. You are also skipping over the SETLOCAL command which will screw up the delayed expansion for your fruit array.

@echo off
SETLOCAL EnableDelayedExpansion
for /F "tokens=1,2 delims=#" %%a in ('"prompt #$H#$E# & echo on & for %%b in (1) do     rem"') do (
  set "DEL=%%a"
)

:fruits
set i=0
for %%a in (apple banana grape lime) do (
   set /A i+=1
   set fruit[!i!]=%%a
)

:food
for /l %%x in (1, 1, 5) do (
call :rand
call :colorEcho 70 !fruit!
echo/
)
pause

exit

:rand
set /a rand=%random%%%4+1
set fruit=!fruit[%rand%]!
GOTO :EOF

:colorEcho
echo off
<nul set /p ".=%DEL%" > "%~2"
findstr /v /a:%1 /R "^$" "%~2" nul
del "%~2" > nul 2>&1
GOTO :EOF

Upvotes: 1

Related Questions