1.

Solve : Subroutines?

Answer»

In a game I'm planning I want the combat sequence to be in a subroutine so that I don't have to keep typing it in With old style basic I used to put;
Gosub 5000, then at the end of the subroutine put RETURN
but this does not seem to work in notepad++ batch files. what is the correct way to call a subroutine and then return from it@ECHO off
REM Batch subroutine demo
REM Use CALL :label
REM with CALL you need the colon!

Echo Subroutine demo
Echo.
Echo In main code
Echo Going to Sub1
Call :Sub1
Echo Back in main code
Echo.
Echo Going to Sub2 with parameters
Call :Sub2 apple pear "quoted parameter"
Echo Back in main code
Echo.
REM need to avoid falling into subroutines
REM the colon is optional with GOTO

REM or use EXIT
Goto :End

:Sub1
Echo In Sub1
Echo Returning...
REM alternative: GOTO :eof
EXIT /B

:Sub2
REM Subroutine with parameters
REM Parameter format & usage is same as
REM from command line however subroutine
REM parameters are distinct from main
REM batch parameters if any

Echo In Sub2
echo Parameter 1 is: %1
echo Parameter 2 is: %2
echo Parameter 3 is: %3

REM REMOVE quotes with tilde modifier
Echo Unquoted Parameter 3 is: %~3

Echo Returning...
EXIT /B

:End
Echo End of Batch
pause

Output...

Subroutine demo

In main code
Going to Sub1
In Sub1
Returning...
Back in main code

Going to Sub2 with parameters
In Sub2
Parameter 1 is: apple
Parameter 2 is: pear
Parameter 3 is: "quoted parameter"
Unquoted Parameter 3 is: quoted parameter
Returning...
Back in main code

End of Batch
Press any key to continue . . .
Many many thanks, this is just what I needed.Also, the subroutines can be batch files.
Makes for more COMPACT code in the main batch.Many thanksIf the subroutine batch file isn't in the current directory then (unless of course you want to specify the path) you can append its path to the end of the PATH ENVIRONMENT variable with either
Code: [Select]PATH %subLocation%;%path%or if you want the CHANGE to be permanent
Code: [Select]SETX path=%subLocation%;%path%
(Just in case you wanted my two cents)



Discussion

No Comment Found