Daniel Hoechle <daniel.hoechle@gmail.com> asked,
> Is there a Mata equivalent to Stata's -capture- statement?
Yes, but it works differently.
Say you are about to call a function and that function has a certain
requirement: Matrix X must be positive definite, variable "mpg" must
exist, etc. The function, let's call it xyz(), will abort with error
if the requirements are not met.
In *SOME* (not all) cases, there will be a corresponding function
_xyz(), and rather than aborting with error, it will return a certain
value if the requirements are not met.
Here are some examples:
stata() and _stata()
Function stata(string scalar cmd) executes cmd. If the command
fails (nonzero return code), function stata() aborts with error.
Function _stata(cmd) executes cmd. Function _stata() returns
a real scalar containing the resulting return code. Function
_stata() never aborts.
fopen() and _fopen()
Function fopen() opens a file and returns a file handle.
fopen("myfile.txt", "r") opens myfile.txt for reading. If
the file does not exist, fopen() aborts with error.
Function _fopen() opens a file and returns a file handle.
_fopen("myfile.txt", "r") opens myfile.txt for reading. If
the file does not exist, fopen() returns a negative value.
There are lots of other examples.
As an aside, and underscore in front of a function name does not mean it works
the way just outlined: All it means is the functions are related, the
_function is a bit more technical. You have to read the documentation to find
out what more technical means. Often, however, it means the function returns
something special on failure, rather than aborting with error.
There are also lots of examples where there is no corresponding _function.
That happens when it is easy enough for you top check the function's
requirements. If you want the equivalent of -capture- when using these
functions, check the requirements.
Here's one example:
Function st_dropvar() drops variables from the Stata dataset.
st_dropvar("mpg") would drop variable mpg, if it exists. If
variable mpg does not exist, st_dropvar() aborts with error.
There is another function, st_varindex(), that returns the
variable number associated with a variable name, or it returns
missing value if the variable does not exist.
Hence, you could code
if (st_varindex("mpg")!=.) st_dropvar("mpg")
When looking at the help on a function, scroll down to the section
Diagnostics. Listed there are the conditions under which the function
will abort with error.
-- Bill
wgould@stata.com
*
* For searches and help try:
* http://www.stata.com/support/faqs/res/findit.html
* http://www.stata.com/support/statalist/faq
* http://www.ats.ucla.edu/stat/stata/