Dear All,
this might be of general interest.
Stata's -tempname- command is used to generate a name within the
current scope (program), which has the following properties:
1) this name is not used by any other objects, which that were
assigned name with -tempname-
2) the object with this name will be destroyed when the current scope ends
Here object is typically a matrix. Note that # 1) is _not_ the same as
"unique", which is a typical confusion. For uniqueness -tempname-
would need to take into account objects created with user-specified
names (which it does not), but since users rarely name their matrices
__000000 - it is almost the same.
Anyways, while debugging a program that was using -tempname- to obtain
a temporary name for a matrix, I needed to peek into the contents of a
matrix to find the source of an error. Since the temporary matrix was
immediately destroyed after an error, I decided to save the contents
of a temporary matrix to something more permanent. Here is what I did:
program define foo_bar
tempname M
matrix `M' = 1
matrix `M'_copy=`M'
matrix dir
end
. matrix drop _all
. program drop _all
. foo_bar
__000000_copy[1,1]
__000000[1,1]
. matrix dir
Surprisingly, the copy of the "more-permanent" matrix has also
vanished, although the name of this matrix was _not_ generated by
-tempname-.
After some experimenting, it seems that rather than doing
(schematically, not literally):
foreach name of tempnameslist {
matrix drop `name'
}
Stata is doing (schematically, not literally)
foreach name of tempnameslist {
matrix drop `name'*
}
which is neither documented, nor safe.
I've checked that it is not doing
matrix drop __*
which also could have been a possible explanation.
I am aware of the documented way to return results from a procedure
via saving results the r(). But there seems to be nothing that forbids
placing the results directly into matrices, and declaring a program
rclass is also sometimes not desirable. The workaround was easy: use
prefix, rather than suffix: matrix copy_`M'=`M'
If anyone is aware of similar issues with tempfile and tempvar, I
would very much like to hear about them.
(copy sent to Stata's tech-support)
Thank you,
Sergiy Radyakin
*
* For searches and help try:
* http://www.stata.com/help.cgi?search
* http://www.stata.com/support/statalist/faq
* http://www.ats.ucla.edu/stat/stata/