Mike Steele
Mike Steele

Reputation: 111

Having an "if" statement remembered throughout the file

So basically I made a batch file where as if the variable %hp% goes below 0, it ends.

@echo off
:start
set /a hp=10
if %hp% LEQ 0 goto ded

:choose
cls
echo %hp%
echo Gain or lose health?

echo 1) Gain
echo 2) Lose
set /p loseorgain=Type Answer Here
if %loseorgain%==1 goto gain
if %loseorgain%==2 goto lose

:lose
set /a hp=%hp%-5
echo You lose 5 hp! You have %hp% left!
pause
goto choose

:gain
set /a hp=%hp%+5
echo You gained +5 hp! You have %hp% left!
pause
goto choose

:ded
echo Ur ded
pause
exit

I want it so that if %hp% drops to or below 0 at any time in the batch file, it will take you to the label "ded"

Instead, it forgets about the if statement once it leaves the :start label.

SIMPLIFIED: I want to have an if statement take an effect throughout an entire batch file, no matter what label it is on.

Is there a way to do this?

Upvotes: 2

Views: 24

Answers (1)

Jason Faulkner
Jason Faulkner

Reputation: 6568

You will need to check the %hp% variable each time, but you can make a common "procedure" to do this. This example should illustrate:

@ECHO OFF
SETLOCAL EnableExtensions

SET hp=5
:Loop
SET /A hp-=1
ECHO You have %hp% HP.
CALL :CheckHP
GOTO Loop

:CheckHP
IF %hp% LEQ 0 (
    ECHO You are dead.
    PAUSE
    EXIT
)

ENDLOCAL

So each time that %hp% could be decremented, you add the line: CALL :CheckHP immediately afterwards which will move control to the "procedure" which checks that the value is still greater than 0. If it is, control will return to the section of the script which made the CALL command.

All you would need to do is just place the CALL :CheckHP line appropriately and maintain all your logic within the CheckHP procedure.

Upvotes: 1

Related Questions