Reputation: 2147
So, I have some nested variables in Batch.
It's causing me an issue.
The reason I have nested variables is because I am emulating an array via:
array[0]=1
array[1]=2
array[2]=3
etc
Now, I have a counter counter
I want to be able to do %array[!counter!]%
, and the output would equal !counter! + 1
.
But I can't.
I think it's because having it surrounded in %
's makes Windows try to expand the variable ASAP, and it does, breaking the counter.
So, instead, why not do !array[!counter!]!
? Well, I tried this, and I think that, instead of interpreting it as (array[(counter)])
, where ()
's are used to show what !!
's are holding, Windows instead interprets it as (array[)counter()
, which is useless to me.
Keep in mind: Whenever I use !!
's, assume I have done setlocal EnableDelayedExpansion
-- I just don't include it as that would be a pain for both me and readers.
Any ideas how to fix this?
Upvotes: 2
Views: 383
Reputation: 2147
This is what I ended up doing:
for /l %%a in (1;1;3) do (
echo !array[%%a]!
)
Originally, I was using a manual counter via variable counter
, but using for /l
means I can have a counter without having to set it to a variable, and, more importantly, not calling it like !varname!
; instead like %%varname
, eliminating confusion.
Upvotes: 0
Reputation: 57252
(at least) Two possible ways. The first is faster and more verbose - CALL
command hits the performance.
@echo off
setlocal enableDelayedExpansion
set array[0]=1
set array[1]=2
set array[2]=3
set counter=0
echo first way :
for /l %%# in (1;1;3) do (
for /f %%$ in ("!counter!") do echo !array[%%$]!
set /a counter=counter+1
)
set counter=0
echo second way :
for /l %%# in (1;1;3) do (
call :subr1 !counter!
set /a counter=counter+1
)
goto :eof
:subr1
echo !array[%1]!
goto :eof
Upvotes: 1