Search code examples
statastata-macros

Inheriting looping variable or local, global macros


main.do is:

foreach mode in mode1 mode2 {

do run.do

}

and run.do is:

foreach y in y1 y2{ 
reg `y' x
outreg2 using `y'.xls, append ctitle(`mode')

}

It has outreg2, so it produced a txt output. But I found that the column title is empty meaning that Stata couldn't get mode.

That implies that the mode loop in main.do was not inherited by run.do.

How can I make it inherited? It would be wonderful if I could choose whether to make it inherited.

What I tried is:

foreach mode in mode1 mode2 {
global mode `mode'
do run.do
}

and:

foreach mode in mode1 mode2 {
local mode `mode'
do run.do
}

and:

foreach mode in mode1 mode2 {
global mode "`mode'"
do run.do
}

But nothing works.


Solution

  • Local macros are .... local. meaning visible only within the same interactive session, program, do-file, or (chunk of) code in a do-file editor window.

    Globals are a crude solution to making stuff visible everywhere, but you must refer to them as such using $. So in your run.do you would need

    ctitle($mode)
    

    Passing the contents as arguments is a much better solution.

    See also the help for include.

    All this is utterly basic Stata programming. To become competent as a Stata programmer, a minimal reference is https://www.stata.com/manuals/u18.pdf, which is also bundled with Stata on your system (unless your version is several years out of date).