1

I'm trying to return an array within a function call, but I'm not sure what I'm doing wrong.

Here's my endlocal &, returning count works fine, but I can't access the changes[x] variable, where x is a number.

Doing echo %changes[0]% shows the correct value but echo %changes[!c!]% does not even when echo changes[!c!] displays changes[0]. I've tried call echo %%changes[!c!]%% and call echo %changes[!c!]%, an idea I got from here, but those don't work either.

endlocal & (
        set "%~2=%count%"
        for /L %%I in (0, 1, %count%) do (
            set /A c = %%I
            echo %changes[!c!]%
        )
    )

Thanks!

Edit: Here's the full function in batch, you'll notice I'm trying a lot of echos randomly at the return part to see if any worked.

:get_changes
    setlocal

    set "changes="
    set /A count = 0
    for /F "tokens=5" %%I in ('my command') do (
        if !errorlevel! neq 0 (
            echo Error while trying to get opened files.
            exit /B !errorlevel!
        )

        if %%I neq change (
            if !count! == 0 (
                set "changes[0]=%%I"
                set /A count += 1
            ) else (
                set exists=0
                call :array_contains changes , !count! , %%I , exists
                if !exists! equ 0 (
                    set changes[!count!]=%%I
                    set /A count += 1
                )
            )
        )
    )

    endlocal & (
        set "%~2=%count%"
        for /L %%I in (0, 1, %count%) do (
            set /A c = %%I
            echo %changes[%%I]%
            echo !changes[%%I]!
            echo %changes[!c!]%
            call echo %changes[!c!]%
            for %%J in (changes[%%I]) do (
                echo !%%J!
            )
        )
    )

    :end_for_get_changes
    exit /B 0
1
Linkxgl
  • 161
  • 4
  • 14
  • Is delayed expansion still enabled after the `endlocal` command? I guess not, so perhaps you should try `call echo %%changes[%%I]%%`... – aschipfl Oct 07 '19 at 22:26
  • @aschipf unfortunately, I've tried that, and it doesn't expand properly either :/ – Linkxgl Oct 07 '19 at 22:31
  • Why did you decide to end the only SetLocal, half way down the code? – Compo Oct 07 '19 at 22:44
  • 1
    So delayed expansion is enabled all the time? Anyway, syntax-wise only `echo !changes[%%I]!` can work (because this expands the index *before* the array element); but you still have got the `endlocal` barrier, which you can pass as illustrated [here](https://stackoverflow.com/a/34427379); take also a look at [this thread](https://stackoverflow.com/q/49041934)... – aschipfl Oct 08 '19 at 12:00
  • @aschipfl I think you're right. This is only one function in the entire batch script, at the beginning I enable delayed expansion, so it gets passed down through this setlocal - that's why it "works" heh – Linkxgl Oct 08 '19 at 14:40

0 Answers0