Search code examples
variablesglobalstatalocalstata-macros

When are global macros deleted?


I have a do file from which I would like to select a few lines of code and then run them using the Execute (do) button. The problem is that there are a bunch of local macros defined in this do file. I can run them, but then in the Stata command prompt the local macros are not accessible. Thus, I think I should just be using global macros.

I have looked in several places and haven't been able to find out what scope macro variables actually have. I realize that local macros are only defined in the instance (for example, a do file) they are originally created in.

But for global macros, are they stored forever and every time I open up a new instance of Stata I will still have the global macros from previous sessions?

Or do they get deleted each time I exit out of Stata (or something else)?


Solution

  • Global means visible everywhere, but not for all time.

    Global macros you create disappear at the end of a session.

    When you start a session, or indeed at any time, macro list shows global and also local macros visible within your current locale. Here "locale" is not a word used in Stata documentation, but a nonce coinage to denote the current interactive session, the current program, the current contents of the do-file editor or a selection thereof, namely the code currently running. The difference is that local macros are only visible within the locale in which they are defined; global macros are visible in any locale.

    Some global macros appear to be created on the fly; thus if I wish for a display of current date or time I can

     di "$S_DATE"
     di "$S_TIME"
    

    and Stata will access the operating system for such details.

    But the easiest way to answer your question is to experiment. Define some global such as

     global whoami "bill999"
     di "$whoami" 
    

    and then sign off and start a new session and see whether it is saved by Stata. Alternatively, save the current dataset and use the same dataset in a new session and see whether globals survive the journey.

    See also help notes.