* Generate localslocal a 1//Local a contains the value 1.local b = 2//Local b contains the value 2.local c = 2 + 2//Local c contains the value 4.local f 2 + 2//Local f contains the value 2 + 2.display"`a'`b'`c'`f'"/* The double quotes are necessary, because "display" would otherwise try to calculate something and return an error message. All five lines have to be executed together. Otherwise, Stata will have forgotten the locals when the display command is executed. */* Caution, set parentheses when calculating with negative numberslocal g = -2di`g'^2// evaluates (-1)*2^2di (`g')^2// evaluates (-2)^2* Generate globalsglobal a 3global b = 4display"`a'`b'$a$b"// Locals and globals can have the same name. Stata doesn't get confused.// Only use globals when you have to, stay local as much as possible* Deleting the content of locals can be done by nothing or "" after the name of your global/localglobal a
global b ""display"`a'`b'$a$b"* Display all currently stored macrosmacro dir* Use extended macro functionssysuse auto.dta, clear// Load example datasetlocal varlist price mpg rep78 headroom trunk weight length turn displacement gear_ratio // Saves variable names in local varlist.local var2: word 2 of `varlist'// Saves second word (here: a variable name) in local var2.local lbl2: variable label`var2'// Saves label of the second variable from varlist.display"`var2' has the label `lbl2'"* $-signs and globalsglobal word hello
display"$14"// This is no problem for Stata as 14 cannot be a macro name.display"$word"// Stata considers $word to be the link to the content of the global word.display"\$word"// Stata prints $word as the backslash tells Stata to consider the $-sign to be a simple character.* Why to use / instead of \ in Windows file pathsglobal myfolder user
display"C:\Windows\$myfolder\file"// Stata displays C:\Windows$myfolder\file because \ prevents $myfolder from being considered a macro.display"C:/Windows/$myfolder/file"/* Stata displays the correct result. Note that Stata evaluates the macro "myfolder" rather than "myfolder/file" because / (or \) tells Stata that the macro ends after myfolder. Therefore macro names cannot contain / or \. */