Home > Back-end >  Using local variables for a function which "returns" a result
Using local variables for a function which "returns" a result

Time:06-14

I'm trying to use local variables in a function but it doesn't work as expected.

@echo off
setlocal

call :Sum %1, %2, sum
echo %sum%
exit /b 0

:Sum
setlocal
set "a=%~1"
set "b=%~2"
set /a "%~3=%a% %b%"
endlocal
exit /b 0

Here is the invocation of the script:

>test.bat 1 2
ECHO is off.

Any clues?

CodePudding user response:

If the expected result is to put sum of arguments into a variable then you'll need to remove setlocal/endlocal inside of :Sum.

:Sum
set "a=%~1"
set "b=%~2"
set /a "%~3=%a% %b%"
exit /b 0

Or you could try a trick from this answer Batch script make setlocal variable accessed by other batch files

Also using of commas as argument delimiters for call isn't encouraged.

CodePudding user response:

You get ECHO is off. because %sum% is not set. Here's an working example:

@echo off
SETLOCAL
CALL :Sum %1, %2, sum
ECHO %sum%
EXIT /B %ERRORLEVEL%

:Sum
SET /A "%~3 = %~1   %~2"
EXIT /B 0

CodePudding user response:

As mentioned by @montonero, the following "hack" solves the problem*:

@echo off
setlocal

call :Sum %1 %2 sum
echo %sum%
exit /b 0

:Sum
setlocal
set "a=%~1"
set "b=%~2"
endlocal & (
    set /a "%~3=%a% %b%"
)
exit /b 0

The command line endlocal & ... works due to the fact that variables are expanded before it is executed, thus creating a bridge between the local and the parent scope.

*https://stackoverflow.com/a/18291599/337149

  • Related