How does this script work?

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
RobinTendo
Posts: 4
Joined: 18 Feb 2021 07:31

How does this script work?

#1 Post by RobinTendo » 01 Mar 2021 02:44

Okay so, this isn't really a problem I'm having, but just a question.

Someone recommended me this script for saving and loading:

Code: Select all

:save
set sav> savegame.sav
cls
echo Progress Saved!
pause>nul
cls
goto gamemenu

Code: Select all

:loadgame
for /f "usebackq delims=" %%x in (savegame.sav) do set "%%x"
cls
echo Game Loaded!
pause>nul
cls
goto gamemenu
What I like about batch is how I understand it. It makes sense to me, like if you do that then that happens and so on. But I dont understand how
for /f "usebackq delims=" %%x in (savegame.sav) do set "%%x"
works. What does it do and why?

T3RRY
Posts: 243
Joined: 06 May 2020 10:14

Re: How does this script work?

#2 Post by T3RRY » 01 Mar 2021 03:40

The command 'Set' when executed with an argument outputs all variables that have a name that begins wit the argument.
'>' Is a redirection operator in batch, so the output of Set gets redirected to the file.
The for loop read the file on a line by line basis and assigns all variables read from the file.

Another way is to reverse the process a bit and use the for loop when "Saving" the variables:
>"%TEMP%\%~n0_Save.cmd" (For /F "Delims=" %%G in ('Set #')Do Echo(Set "%%G")

Then to load you can just call the cmd save file.

The usebackQ in your posted example should be accompanied with quoted filepath in the For (SET), which ensures the command doesn't fail if there's spaces in the filepath.

Post Reply