Home Upgrade Search Memberlist Extras Hacker Tools Award Goals Help Wiki Contact

Shell 

Using SETLOCAL and ENDLOCAL inside functions

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 :eof

The 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.

  1. X is globally defined at the top of the script

  2. Continue to the :main function, and display %x%

  3. Call :function_1 using SETLOCAL to temporarily redefine %x%

  4. Display global %x% inside :main function to show %x% has NOT changed

  5. Call :function_2 WITHOUT SETLOCAL to redefine %x%

  6. Display in :main function that %x% has been globally modified



This concludes my quick tutorial. If you have any questions feel free to ask!
You guys here have advanced so much since my last relative post in this section. Good to see that flawless tutorials with the code/explanation format are still being posted focusing on everything but the stereotypical Batch viruses. Awesome work.
[Image: chain.png]
(Nov 13, 2016 01:53 PM)Sajuuk Wrote:  You guys here have advanced so much since my last relative post in this section. Good to see that flawless tutorials with the code/explanation format are still being posted focusing on everything but the stereotypical Batch viruses. Awesome work.

I agree. Good work @OP!


Possibly Related Threads...
Thread / Author Replies Views Last Post
[C] by NicktronJul 29, 2015 04:01 AM 6 115 Jul 29, 2015 04:01 AM
Last Post: Nicktron
[Java] by TizenDec 13, 2014 07:58 PM 10 324 Dec 13, 2014 07:58 PM
Last Post: Tizen
[Shell] by White LightJan 11, 2014 11:58 PM 3 152 Jan 11, 2014 11:58 PM
Last Post: ɩᴄᴀʀᴜȿ ᴌוᴠᴇѕ™