Reputation: 681
I know how you can use for /L, delayedexpansion, and arrays to create nested variables in batch files, but please hear out my scenario.
I have 400 variables created dynamically, that look like this:
%1x1% %1x2% etc. %2x1% %2x2% etc. and it goes up to 20x20.
if the user requests to change 20 x 20, they type in "20 20" and it's parsed. I'm able to set 20x20 to 0, for example, then. My problem is checking it. I want to be able to change it back to "." (which is what it is before the user requests to set it to 0) if they type in "20 20" again.
This is what it kind of looks like:
set !xVal!x!yVal!=0
How can I achieve this:
if %!xVal!x!yVal!%==0
without rewriting my whole script? Keep in mind I said it's created dynamically, so it's not a problem if I need to set up an array, which I'm not sure that will even work. That is essentially 2 for loops to create a "grid" of variables, the 1x1 to 20x20.
Upvotes: 1
Views: 291
Reputation: 67206
I think your problem have two main different points:
1- You never should define any variable that start in digit, like set 1x1=0
. Why? Because when you try to expand its value this way: echo %1x1%
the first "%1" is taken as the first parameter of the Batch file, so you will never get the value of "1x1" variable. I suggest you to insert a letter at beginning of the variable name; for example: set a1x1=0
.
2- You use the wrong method to expand the variable value. Here are some examples:
Create the 20 x 20 array:
for /L %%i in (1,1,20) do (
for /L %%j in (1,1,20) do (
set a%%ix%%j=0
)
)
Set the value of element xVal and yVal:
set a!xVal!x!yVal!=0
Get the value of element xVal and yVal:
echo !a%xVal%x%yVal%!
Get the value of element xVal and yVal when both indices change inside a code block:
for %%x in (!xVal!) do for %%y in (!yVal!) do echo !a%%xx%%y!
The same, but using just one FOR:
for /F "tokens=1,2" %%x in ("!xVal! !yVal!") do echo !a%%xx%%y!
For a complete description of these array managements, see this post.
Upvotes: 1