Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How Do I Subtract Variables in Batch

Tags:

batch-file

I am making a text based game in batch, i need to subtract the gold of the player from the cost of the weapons/armor...can someone look at my code and tell me if they see something wrong with this?

@echo off 
set gold= 20

echo %gold%
pause >nul
goto blacksmith
:blacksmith
set /p weaponch=  Purchase: 

if %weaponch%==1s (
set  weaponch= 10
set a/ gold=%gold%-10
echo.
echo Gold: %gold% You have purchased the Light Sword
pause 
)
like image 393
Moustachio Avatar asked Oct 25 '25 04:10

Moustachio


1 Answers

Your had two problems in your code.

The first was fixed by user328430s answer, where you used a/ instead of /a, and also -= is easier.

The other problem is that batch fills in all the instances of %gold% in your if at once, as soon as it gets to it, and so it does not recognize the change until after. I suppose this is for optimization, but it leads to problems. To fix it you have to enable delayed expansion in your program, and then within the if you have to remind it to use delayed expansion for the gold variable. This is done by first using the command:

setlocal enabledelayedexpansion

and then switching

echo Gold: %gold% You have purchased the Light Sword

with

echo Gold: !gold! You have purchased the Light Sword

Adding that with the corrected subtraction line, you get:

@echo off 
setlocal enabledelayedexpansion
set gold= 20

echo %gold%
pause >nul
goto blacksmith
:blacksmith
set /p weaponch=  Purchase 

if %weaponch%==1s ( 
set  weaponch= 10
set /a gold-=10
echo.
echo Gold: !gold! You have purchased the Light Sword
pause 
)

I tested that on my computer, and inputed 1s for the purchase and it worked as it should. Hope that helps.

like image 152
rp.beltran Avatar answered Oct 27 '25 01:10

rp.beltran



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!