Nov 13, 2016 12:11 PM
(This post was last modified: Nov 13, 2016 08:52 PM by ɩᴄᴀʀᴜȿ ᴌוᴠᴇѕ™.)
Code
@echo off
rem set GLOBAL variable x
set "x=Hello World"
:main
cls
echo.
echo MAIN
echo X is globally defined as - %x%
echo.
pause
echo.
echo Calling function with setlocal
call :function_1 "dlroW olleH"
echo.
echo MAIN
echo X is globally defined as - %x%
echo.
pause
call :function_2 "HeLlO wOrLd"
echo.
echo MAIN
echo X is now globally redefined as - %x%
echo.
pause
exit
:function_1
SETLOCAL
rem define LOCAL variable X
set "x=%~1"
echo.
echo FUNCTION 1
echo Create local variable X - %x%
echo.
pause
ENDLOCAL
goto :eof
:function_2
rem redefine GLOBAL variable X
set "x=%~1"
echo.
echo FUNCTION 2
echo Globally redefine variable X - %x%
echo.
pause
goto :eofThe code above demonstrates two functions being called inside the :main function. The purpose of this quick tutorial is to demonstrate how setlocal can be useful when used in functions that display output, and keep your variable environment pool small. Creating scripts that have A LOT of variables will run slower than a script with less variables. This is good to know for development in batch games where there could be MANY variables.
Step by step in plain english.
- X is globally defined at the top of the script
- Continue to the :main function, and display %x%
- Call :function_1 using SETLOCAL to temporarily redefine %x%
- Display global %x% inside :main function to show %x% has NOT changed
- Call :function_2 WITHOUT SETLOCAL to redefine %x%
- Display in :main function that %x% has been globally modified
This concludes my quick tutorial. If you have any questions feel free to ask!


![[Image: chain.png]](https://i.postimg.cc/NFnfH9zY/chain.png)