Page 1 of 1

How to expand variable in another variable with string substitution?

Posted: 11 Jan 2020 15:19
by Lowsun
Sorry about the confusing title, but I couldn't think about any other way to word it. Basically, I have some variables, for example:

Code: Select all

SET var[1]=12
SET var[2]=23
And another one, which contains the "var" prefix, but not that specific number, like:

Code: Select all

SET displayvar=%var[#]%
I'm trying to use it like:

Code: Select all

SET /A var=%displayvar:#=1%
To hopefully get the value of %var[1]%, but obviously it's already been expanded when it was SET above, so it gives nothing. I've tried doubling the %% and using CALL SET, but so far to no avail. Using DELAYEDEXPANSION isn't an option either, since I'm substituting variables with delayed expansion already.

Any tips or guidance would be much appreciated.

Thanks in advance, Lowsun :)

Re: How to expand variable in another variable with string substitution?

Posted: 11 Jan 2020 20:57
by Eureka!
With delayedexpansion enabled:

Code: Select all

setlocal enabledelayedexpansion
SET var[1]=12
SET var[2]=23

set #=1
SET displayvar=!var[%#%]!
set displayvar

With delayedexpansion disabled:

Code: Select all

setlocal 
SET var[1]=12
SET var[2]=23

set #=1
call SET displayvar=%%var[%#%]%%
set displayvar
Using your substitution method:
(Why the extra complication?)

Code: Select all

setlocal
SET var[1]=12
SET var[2]=23

set step1=%%var[#]%%
set step2=%step1:#=1%
call set display=%step2%

set step
set display

Re: How to expand variable in another variable with string substitution?

Posted: 11 Jan 2020 21:36
by dbenham
Your technique can work if you simply define displayvar properly. It works because SET /A can expand a variable on its own.\

Code: Select all

@echo off
setlocal
SET var[1]=12
SET var[2]=23
set "displayvar=var[#]"
set /a var=%displayvar:#=1%
echo %var%
--OUTPUT--

Code: Select all

12
But why on earth are you structuring things this way :?: :?

Re: How to expand variable in another variable with string substitution?

Posted: 11 Jan 2020 21:49
by Lowsun
Thanks Eureka and dbenham. I ended reworking all the code I was doing, since it was getting unwieldy down the line. Turns out I was over complicating a lot of stuff. But thanks for taking the time help :D