0

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?

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

You're welcome. Though I wouldn't rely much on tricks since they aren't documented and not very reliable.
I agree in general but in this case it seems to be the only workaround.
0

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

1 Comment

What I'm looking for is a solution for the general case as described by the title of the question. My example was just an illustration; to add two command-line arguments I don't even need to define a function.
0

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 the command line is executed, thus creating a bridge between the local and the parent scope.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.