desktop-save-mode will do this for you. It saves more than just the state of variables though, it also saves open buffers, window layouts and more.
To explicitly save the value of a global variable with you desktop, add the symbol to the list:
desktop-globals-to-save. For local variables, use
You can read more about
desktop-save-mode here to learn about enabling and customizing it.
Alternatively, persisting your scratch buffer between sessions so you could reevaluate customizations may suffice for your example. persistent-scratch is available on MELPA and simplifies the process of saving your scratch buffer between sessions.