If statement variable problem

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
PlateauRealm
Posts: 1
Joined: 21 Aug 2021 16:54

If statement variable problem

#1 Post by PlateauRealm » 21 Aug 2021 17:00

I'm a little baffled by this batch code here.
I have similar code structure before and outside of a conditional 'if' statement, but the rand2 value
inside the conditional is always seen as a zero value in the 'set hexa2=!HEXA:~%rand2%,2!' line.

Code: Select all

@echo off
cls

SETLOCAL ENABLEDELAYEDEXPANSION

set HEXA=1B1F2E303E474E4F575E5F6087909FA0B0D0D7DFE0F4

:THIS_WORKS
set /A rand1=%random% %% 22
set hexa1=!HEXA:~%rand1%,2!
color !hexa1!

pause

cls

set WONKY=ZZ

:THIS_DOES_NOT_WORK_AS_INTENDED
if "!WONKY!"=="ZZ" (
	echo Inside the 'if' conditional. Good so far.
	set /A rand2=%random% %% 22
	echo rand2 is a new random number every time: !rand2!	Good so far, but
	echo  rand2 is always interpreted as a '0' value in the following 'set hexa2=...' line
	set hexa2=!HEXA:~%rand2%,2!
	color !hexa2!
	echo  and color ^^!hexa2^^! always results in a screen / text color of '1B'
)

pause

:END
What obvious thing have I overlooked here? The code structure seems straight-forward enough.

Thanks.
Last edited by aGerman on 22 Aug 2021 04:36, edited 1 time in total.
Reason: code formatting

aGerman
Expert
Posts: 4245
Joined: 22 Jan 2010 18:01
Location: Germany

Re: If statement variable problem

#2 Post by aGerman » 22 Aug 2021 05:16

The %rand2% in set hexa2=!HEXA:~%rand2%,2! needs delayed expansion in order to access the updated value. However, nesting of two variables won't work if both variables use exclamation points. One of the possible workarounds is to cache the value in a FOR variable.
Also, since you have 22 pairs of hex digits in your string you'll need to double the 0..21 the modulo operation yields.

Steffen

Code: Select all

@echo off
SETLOCAL ENABLEDELAYEDEXPANSION

set "HEXA=1B1F2E303E474E4F575E5F6087909FA0B0D0D7DFE0F4"
set "WONKY=ZZ"

if "!WONKY!"=="ZZ" (
	set /A "rand2=!random! %% 22 * 2"
	for %%i in (!rand2!) do color !HEXA:~%%i,2!
)

pause

Post Reply