*! version 2.1.0 10oct2023
preserve_globals -- Preserve global macros

Syntax

preserve_globals
[ , strict : ]
command

Description

preserve_globals preserves global macros and restores their contents
when command has concluded.
Any changes that command makes to
existing global macros are undone as soon as command concludes.
However, command may define new global macros and such global
macros persist when command concludes.

Options

strict deletes any new global macros that command defines
when command concludes.

Remarks

Generally, preserve_globals may be used with commands
that define local macros, e.g., levelsof.
However, local macros cannot be deleted by commands prefixed
with preserve_globals.
Consider this example:

. sysuse auto
. local foo "42"
. preserve_globals levelsof price if make == "", local(foo)

In auto.dta, the variable make is never missing.
Thus, levelsof would not return any levels of the variable
price; the local macro foo should be empty.
Yet, the local macro foo will remain unchanged;
it still contains "42".

When you use preserve_globals with commands that define local macros,
you must define the respective local macros explicitly; that is, you must
type

local levels // void
levelsof varname, local(levels)

to guarantee that local macros are empty when they should be empty.

Acknowledgements

Earlier versions of the command resulted from a suggestion from Clyde Schechter
and a following discussion on
Statalist.

Support

Daniel Klein

klein.daniel.81@gmail.com