I am working with an .ado file named flow
. If the user types flow i
I want one if
statement to run. If the user types flow e
, I want another if
statement to run.
How do I do this?
Many readers of this forum expect to see some code that you tried....
program flow
version 8 // will work on almost all Stata in current use
gettoken what garbage : 0
if "`what'" == "" | "`garbage'" != "" | !inlist("`what'", "e", "i") {
di as err "syntax is flow e or flow i"
exit 198
}
if "`what'" == "e" {
<code for e>
}
else if "`what'" == "i" {
<code for i>
}
end
The last if
condition is redundant as we've already established that the user typed e
or i
. Edit it out according to taste.
Given your comment on the answer by @NickCox, I assume you tried something like this:
program flow
version 8
syntax [, i e]
if "`i'`e'" == "" {
di as err "either the i or the e option needs to be specified"
exit 198
}
if "`i'" != "" & "`e'" != "" {
di as err "the i and e options cannot be specified together"
exit 198
}
if "`e'" != "" {
<code for e>
}
if "`i'" != "" {
<code for i>
}
end
After that you call flow
like this: flow, i
or flow, e
. Notice the comma, this is now necessary (but not in the command by @NickCox) because you made them options.
If you want i
and e
to be mutually exclusive options, then this is yet another alternative:
program flow
version 8
capture syntax , e
if _rc == 0 { // syntax matched what was typed
<code for e>
}
else {
syntax , i // error message and program exit if syntax is incorrect
<code for i>
}
end
If the code in each branch is at all long, many would prefer subprograms for each case as a matter of good style, but that would be consistent with the sketch here. Note that in each syntax
statement the option is declared compulsory.
The effect of capture
is this: errors are not fatal, but are "eaten" by capture
. So you need to look at the return code, accessible in _rc
. 0 for _rc
always means that the command was successful. Non-zero always means that the command was unsuccessful. Here, and often elsewhere, there are only two ways for the command to be right, so we don't need to know what _rc
was; we just need to check for the other legal syntax.
Note that even my two answers here differ in style on whether a user typing an illegal command gets an informative error message or just "invalid syntax". The context to this is an expectation that every Stata command comes with a help file. Some programmers write on the assumption that the help file explains the syntax; others want their error messages to be as helpful as possible.