0

I want to change the name of a variable within a batch file because that way I wouldn't have to type out the same code 24 times.

I would like something like this but that actually works:

set n=1
set t=1

:loop

set /p %n%%t% = this will be variable %n%%t%:

echo %%n%%t%%

set /a n+=1
set /a t+=1

goto loop
Tholleman
  • 13
  • 3
  • 3
    `but that actually works` - so what's the problem? – npocmaka Mar 19 '16 at 20:06
  • 1
    There are so many "real" scripting languages you can use on Windows - I strongly urge you to *AVOID* using .bat files except for the most simplistic of tasks. VBScript and Powershell are two *far superior*, built-in options. IMHO... – paulsm4 Mar 19 '16 at 20:09
  • I suggest you to read [Arrays-linked-lists-and-other-data-structures-in-cmd-exe-batch-script](http://stackoverflow.com/questions/10166386/arrays-linked-lists-and-other-data-structures-in-cmd-exe-batch-script/10167990#10167990) – Aacini Mar 19 '16 at 22:34

3 Answers3

1

You can use an array for that. Try this:

set arrayline[%n%][%t%] = this will be variable %n%%t%:
redent84
  • 18,901
  • 4
  • 62
  • 85
1

Consider FOR /L instead of goto - it will work faster and the code will more maintanable.Though you'll need also delayed expansion

@echo off
setlocal enableDelayedExpansion
set n=1
set t=1


for /l %%# in (1;1;24) do (

    set /p element[!n!][!t!]= enter the value of element[!n!!t!] : 
    set /a n+=1
    set /a t+=1
)
(echo()
echo listing elements:
(echo()
set element

endlocal

Mind that if you left spaces around = when you assign value of a variable the space will become part of the variable name.

npocmaka
  • 55,367
  • 18
  • 148
  • 187
1

Two errors.

First is that you've included a space in the variable being set, as already noted.

Second is that you can't use echo with variablenames that start with a numeric.

You can see the variable using set 1 (for instance) so it would be possible to use something like for /f "tokens-1*delims==" %%a in ('set 1') do if "%%a"=="1" echo %%b

for instance, to extract the value of the environment variable 1

BUT - it's a whole lot easier to simply use variablenames that don't start with numerics.

%n where n is 0..9 refers to parameter n to the routine in question.

Magoo
  • 77,302
  • 8
  • 62
  • 84