Stata: Check if a local macro is undefined

The question asked for an idiomatic way to do this and across Stata programmers

 if "`macroname'" != "" 

is far by the most commonly used test of whether a macro is defined. Macros contain strings when they are defined, and this is the general usage; use of numeric characters is just a special case.


If it's undefined, the contents of the macro would be empty. You can do this:

if missing(`"`mymacroname'"') {
    display "Macro is undefined"
}

The quotes aren't really needed if the macro will contain a number. The missing(x) function can handle strings and numbers. It is kind of like testing (x=="" | x==.) Placing `' around "`mymacroname'" allows the macro to contain quotes, as in local mymacroname `"foo"' `"bar"'.


OP asked if there was a way to test if a local is undefined. The concept of defined/undefined doesn't really exist in Stata (which is confusing to users new to Stata but not new to programming).

A more Stata like way to think about this is if the local is missing or not missing. If a local has not been defined it is considered missing. But if a local has been defined to a missing value, like the empty string "", it is also considered missing.

So, there is no way in Stata to differentiate between a string local being undefined or being defined but contains a missing value, i.e. the empty string "". Both the answers already given does not capture the difference between localA (defined but as the empty string) and localB (undefined) in the example below:

*initiating localA to the empty string
local localA ""

*Both these conditions will evaluated identically
if missing("`localA'")
if missing("`localB'")

*Both these conditions will evaluated identically
if "`localA'" != "" 
if "`localB'" != ""