Search code examples
batch-filecommanddos

*Batch* Repeat a block of commands in multiple locations?


I am writing a mini batch program with a moving "@" in a grid of 3x3.
I am looking to use this block of code in 5 places:

if %face%==up set /a x=%x%+1  
if %face%==left set /a y=%y%+1  
if %face%==down set /a x=%x%-1  
if %face%==right set /a y=%y%-1  

(x and y's are mixed up but don't worry about that)

I could copy paste it a few times but i would like to know if there is a better way of doing it :)

So I want a "variable" containing that code and put the "variable" in the places where I need it instead of copy pasting it...


Solution

  • you can make a sudo-function like:

    goto skip_face_func
    :face_func
    set x=%1
    set y=%2
    if not defined x set x=0
    if not defined y set y=0
    if %face%==up set /a x=%x%+1  
    if %face%==left set /a y=%y%+1  
    if %face%==down set /a x=%x%-1  
    if %face%==right set /a y=%y%-1 
    goto :eof
    :skip_face_func
    
    
    :: Making x=1 y=4
    call :face_func 1 4
    echo x:%x% y:%y%
    
    :: Making x=5 y=2
    call :face_func 5 2
    echo x:%x% y:%y%