1

I am currently using this method from "jeb" to handle many variables. BAT-file: variable contents as part of another variable

setlocal EnableDelayedExpansion
set arr[1]=17
set arr[2]=35
set arr[3]=77
(
  set idx=2
  set /a var=arr[!idx!]
  echo !var!
)

Works well. The problem is that I need to set the value of some variables again. All my attempts have failed miserably.

set set arr[!idx!]=test
call set arr[!idx!]=test
set !arr[!idx!]!=test
Community
  • 1
  • 1
  • To set an element of the var you don't need to use delayed expansion, only to output the content. `set arr[%idx%]=test`, `Echo !arr[%idx%]!` or `call echo %%arr[%idx%]%%` If being in a (code block) it gets more difficult. –  Mar 27 '17 at 17:06
  • See: [this answer](http://stackoverflow.com/questions/10166386/arrays-linked-lists-and-other-data-structures-in-cmd-exe-batch-script/10167990#10167990) – Aacini Mar 28 '17 at 01:32

2 Answers2

1

Your question is not clear. I don't understand what you mean with "I need to set the value of some variables again". You should describe what you expect and what you really get instead. For this reason I can't offer an exact answer to your question, but just a series of examples:

echo off
setlocal EnableDelayedExpansion

rem The target variable is "b1" or "b2", depending on *current* value of "i":
set i=1
set b1=var1
set b2=var2
call echo %%b%i%%%

rem This works, but only *outside parentheses*
set b%i%=var1changed
call echo %%b%i%%%

rem Inside paren, this works only when "i" var is not changed:
(
set b%i%=var1changed again
call echo %%b%i%%%
set i=2
set b%i%=wrong: this should be b2, but it is b1
call echo %%b%i%%%
)
set b

rem Using delayed expansion for the index works always:
(
set i=1
set b!i!=var1 again, inside paren
call echo %%b!i!%%
set i=2
set b!i!=var2changed
call echo %%b!i!%%
)
set b

Output:

var1
var1changed
var1changed again
wrong: this should be b2, but it is b1
b1=wrong: this should be b2, but it is b1
b2=var2
var1 again, inside paren
var2changed
b1=var1 again, inside paren
b2=var2changed

You may also use a FOR /F command for this management. Further details at this answer.

Community
  • 1
  • 1
Aacini
  • 65,180
  • 12
  • 72
  • 108
0

I found (in the jeb link itself) a solution without any elegance, and I still have to change all my script, so I still await a response.

set i=1
set b1=var1
call echo %%b%i%%%
set b%I%=var1changed
call echo %%b%i%%%