arraysbatch-filesubroutine

passing array in as subroutine argument in batch file


I have the following code:

@echo off

setlocal EnableDelayedExpansion

set array1[1]=1
set array1[2]=2

set array2[1]=3
set array2[2]=4

call :whatever %array1%
call :whatever %array2%

goto :eof

:whatever
echo value of first array element is %1[1]
echo value of second array element is %1[2]
goto :eof

Basically, I have 2 arrays, each holding 2 values, and I want to pass each array as an argument in a subroutine, and then print the respective values of each array in that subroutine. So I'm ultimately trying to print the following:

value of first array element is 1
value of second array element is 2
value of first array element is 3
value of second array element is 4

Unfortunately, my above code is not printing the above values that I want. Anyone know a way to do this?

Thanks.


Solution

  • Batch doesn't have arrays in the sense that there are array objects; there are just collections of variables that all have the same prefix that you happen to be able to iterate over because of how the interpreter parses scripts.

    What you can do, however, is pass the name of the arraylike as an argument to the subroutine and then use delayed expansion (which you already have enabled) to refer to the variables that you're trying to access.

    @echo off
    
    setlocal EnableDelayedExpansion
    
    set array1[1]=1
    set array1[2]=2
    
    set array2[1]=3
    set array2[2]=4
    
    call :whatever array1
    call :whatever array2
    
    goto :eof
    
    :whatever
    echo value of first array element is !%~1[1]!
    echo value of second array element is !%~1[2]!
    goto :eof