Notice: On April 23, 2014, Statalist moved from an email list to a forum, based at statalist.org.
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
st: Confusion over locals?
From
Nick Cox <[email protected]>
To
[email protected]
Subject
st: Confusion over locals?
Date
Thu, 21 Apr 2011 00:35:39 +0100
Recently I have seen two strange practices in defining local macros.
They are legal, as otherwise the code would not work, but they do seem
indicate confusion. I've seen examples of these in recently posted
programs on SSC and in code on this list.
I can't see any case whatsoever for either of these practices. Nesting
of macros is often necessary and useful, but it's not needed in the
examples here. The main issue is stylistic. No one benefits from
unclear or unnecessarily complicated code, least of all the
programmer.
(1)
tempname mymacro
local `mymacro' "stuff"
local `mymacro' "``mymacro'' more stuff"
Authors here to be influenced by the -tempname-/-tempvar- syntax which
is used to get temporary names for variables, scalars, matrices, etc.
But that it is not needed here. You just say what name you want for a
local macro, and if it's a legal name it's yours.
(If the local macro is already defined, your new definition overwrites
the old, so don't do that if you don't want it.)
So, the code above has one level of reference too many. You just go
local mymacro "stuff"
local mymacro "`mymacro' more stuff"
(2)
local a "b"
...
local `a' "c"
What authors intend here is less clear. The thinking may be that if a
local macro is already defined, as in the first statement, then the
second statement is the way to re-define it. But that's wrong. The
syntax for definition is the same regardless of whether a local macro
exists already. The effect of the second statement is to define a
second local macro with new name -b- and contents "c". The rule is
that macro references are always interpreted before Stata attempts to
execute the command.
Trying out little definitions and then using -mac li- to see the
results is a simple and valuable of checking what you are doing.
It would no doubt seem dogmatic to say that the second form is never
useful, but I've not noticed it in reading and never to my
recollection used it in writing.
Others may have comments on whether I am correct that these errors
seem to have emerged recently despite now several years' history of
Stata programming --- or indeed comments on related questions.
Nick
P.S. the issue of "delayed macro substitution" is different. I vented
my distaste for this practice in Gabi Huiber's blog at
http://enoriver.net/index.php/2011/02/10/delayed-macro-substitution/
*
* 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/