Nesting locals and globals

Nesting locals and globals

* Nested locals
local x1 = 1
local x2 = 5
local x3 = 10
local i  = 1
local j  = 3
display `x1' 		// Stata displays local x1.
display `x`i''		// Stata first expands `x`i'' to `x1' and then to 1 which is the content of x1.
display `x`j''		// Stata first expands `x`j'' to `x3' and then to 10 which is the content of x3.
display `x'`j'		// Stata first expands `x'`j' to `j' because no local x is defined (hence considered empty) and then to 3 which is the content of j.

* Nested globals
global x1 = 1
global x2 = 5
global x3 = 10
global i  = 2
display "$x$i"		// Stata first expands $x to nothing and then $i to 2.
display "${x$i}"	// Stata first expands $i to 2 and then $x2 to 5.

* Globals followed by text
local a number
global a number
display "`a'1"		// Stata displays number1, as the apostrophe marks the end of the local.
display "$a1"		// Stata displays nothing because it is looking for the global a1 which does not exist.
display "${a}1"		// Stata display number1 because the curly brackets mark the end of the global.

* Linking macros
global varlist var1 var2
global newlist $varlist var3
display "$newlist" 	// Results in var1 var2 var3.
global varlist var1
display "$newlist" 	// Still results in var1 var2 var3 because the macros are not linked.

global varlist var1 var2
global newlist \$varlist var3
display "$newlist" 	// Results in var1 var2 var3.
global varlist var1
display "$newlist" 	// Results in var1 var3 because Stata first expands varlist and then newlist.