Reputation: 14106
I am writing a Stata do
file and I would like to provide default values if the user does not supply some parameters. To do so, I woud like to check if a macro is undefined.
I have come up with a hacky way to do this:
*** For a local macro with the name value:
if `value'1 != 1 {
...do stuff
}
But I would like to know if there is a idiomatic way to do this.
Upvotes: 9
Views: 7925
Reputation: 1037
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"'
.
Upvotes: 9
Reputation: 3255
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'" != ""
Upvotes: 3
Reputation: 37208
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.
Upvotes: 7