Page 1 of 1

How does this script work?

Posted: 01 Mar 2021 02:44
by RobinTendo
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?

Re: How does this script work?

Posted: 01 Mar 2021 03:40
by T3RRY
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.