BrickMan
BrickMan

Reputation: 37

In batch, how to add spaces to variables?

I am creating a game. The character moves when the player presses A or D. My question that I have: How to add spaces to these variables in batch? I have this code that set blank variables for the player and the enemy:

set right=
set left=
set leften=
set righten=

Upvotes: 1

Views: 3482

Answers (1)

Magoo
Magoo

Reputation: 80023

set "right= "

Always a good idea to use quotes in set string-commands.

Demo using advanced techniques...

@ECHO OFF
SETLOCAL

:: a variable with many spaces

SET "spaces=                    "

SET "myvar="
ECHO Hello%myvar%World

CALL :addspaces myvar 2

ECHO Hello%myvar%World

CALL :addspaces myvar 3

ECHO Hello%myvar%World

SET "mynewvar=Another"

ECHO %mynewvar%Spaces

CALL :addspaces mynewvar 3

ECHO %mynewvar%Spaces

ECHO ----------------Another method --------

SET "myvar="
ECHO Another%myvar%method

CALL :addchars myvar 2

ECHO Another%myvar%method

CALL :addchars myvar 3 x

ECHO Another%myvar%method

SET "mynewvar=Batch is "

ECHO %mynewvar%easy

CALL :addchars mynewvar 13 "so "

ECHO %mynewvar%easy

PAUSE
GOTO :eof

:: To variable name %1, add %2 spaces

:addspaces
CALL SET "%1=%%%1%%%%spaces:~-%2%%"
GOTO :eof

:: To variable name %1, add %2 of %3;spaces if %3 is missing

:addchars

FOR /L %%Z IN (1,1,%2) DO IF "%~3"=="" (CALL SET "%1=%%%1%% ") ELSE (CALL SET "%1=%%%1%%%~3")

GOTO :eof

The two subroutines require explanation.

Because of the way cmd operates, in the :addspaces routine, the set is CALLed and the following substitutions are made before execution - reading left-to-right

set "%1=%%%1%%%%spaces:~-%2%%"

first, substitute the parameter values for %1..%9

set "parameter1=%%parameter1%%%%spaces:~-parameter2%%"

Next, observe escape-sequences, % escapes %

set "parameter1=%parameter1%%spaces:~-parameter2%"

When this command is executed, it's re-parsed as

set "parameter1=contents of parameter1%spaces:~*contents of**parameter2*%"

The second routine is another approach, same parsing trick used but this time adding the third parameter which may be a character or a string and if the string to be repeated contains a separator character like a space, then it must be "quoted".

Upvotes: 3

Related Questions