2

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?

Quelklef
  • 1,999
  • 2
  • 22
  • 37
  • All array management details are expalined at [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 Jun 24 '15 at 19:41
  • Yes, I understand this. This does not have to do with arrays, but instead with nested variables in general. – Quelklef Jun 24 '15 at 21:28
  • The problem is already solved, by the way, in case you were going to answer :] – Quelklef Jun 24 '15 at 21:30
  • 1
    If the problem is solved then you should inform this point to the community selecting one of the answers. I just wanted to note that the `call echo %%array[!counter!]%%` notation (that use `counter` variable as index) and the `for /L %%i in (1,1,3) do echo !array[%%i]!` method (that don't require the index variable) are both explained with detail at that link... – Aacini Jun 24 '15 at 22:03

2 Answers2

1

(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
npocmaka
  • 55,367
  • 18
  • 148
  • 187
0

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.

Quelklef
  • 1,999
  • 2
  • 22
  • 37