1

Say I have set a few variables...

set x=1
set y=1
set x1y2=J
set x%x%y%y%=Y

In the game I am creating using cmd, the name of the variable x%x%y%y% changes very often, because x and y are always changing and x%x%y%y% is dependant x and y.

Now I want to use an if statement to check the value of x2y2.

if %x%x%y%y%%=J echo Yay

The two percent sign at the beginning and end are to call the variable, but the percent signs inside are also calling variables.

Use this to help visualise it (I know, it's confusing)

  This is all one big variable
 ______________|______________
|                             |
%    x   % x %   y   % y %    %
     |   |___|   |   |___|
A letter   |  A letter |
These two are smaller variabels set previously

But obviously the syntax is correct, because there is no variable called '1x1y' and there is an extra %. And remember, I can't just type the variable name because the some variables are always changing. What do I do..?

If you're confused, please ask questions, and if it is lacking anything feel free to post that in the comments too.

Thanks in advance.

Oditi
  • 23
  • 5
  • I suggest you to read [this post](http://stackoverflow.com/questions/10166386/arrays-linked-lists-and-other-data-structures-in-cmd-exe-batch-script/10167990#10167990) – Aacini Aug 22 '16 at 12:43

2 Answers2

2

try with delayed expansion:

@echo off
set x=1
set y=1
set x1y2=J
set x%x%y%y%=Y

setlocal enableDelayedExpansion

if "!x%x%y%y%!" equ "Y" echo yep
jeb
  • 78,592
  • 17
  • 171
  • 225
npocmaka
  • 55,367
  • 18
  • 148
  • 187
1

As an alternative to delayed expansion illustrated by this answer, you could use call, together with doubling the % signs of the "outer" variable; you will need an interim variable (cmp) then:

set "x=1"
set "y=1"
set "x1y2=J"
set "x%x%y%y%=Y"

call set "cmp=%%x%x%y%y%%%"

if "%cmp%"=="J" echo Yay

What happens, how does it work?
Well, call introduces another parsing phase of the command interpreter, so...:

call set "cmp=%%x%x%y%y%%%"

..., after the first parsing phase, becomes...:

call set "cmp=%x1y1%"

..., because two consecutive %% become a single literal %; %x% and %y% are expanded during that phase too; finally, after the second parsing phase, the "outer" variable becomes expanded and therfore, the command line becomes:

set "cmp=Y"

Note that this method may fail in case the "outer" variable contains " and/or other special characters, where the method using delayed expansion is robust against all them.


By the way, I recommend to generally use the syntax set "VAR=Value" rather than set VR=Value in order to be safe against poisonous characters and to not include potential trailing white-spaces in the variable value.

Community
  • 1
  • 1
aschipfl
  • 33,626
  • 12
  • 54
  • 99