Consider this example:
\documentclass{article}
\begin{document}
\def\something{something}
\something
{
\def\something{another thing}
\something
}
\something
\end{document}
From the output it can be seen that there are two variables something
each living in their own scope:
Now, I put a variable to live inside a newcommand
:
\documentclass{article}
\def\something{something}
\newcommand{\dosomething}{
invoking ``dosomething''
\def\something{another thing}
\something
}
\begin{document}
\something
\dosomething
\something
\end{document}
From output it can be seen that invoking the newcommand
altered the previous definition of the variable:
This can lead to obscure errors particularly with libraries involving hundreds of variables. Is there a way to protect my variables from being altered by newcommand
s? What is the best approach?
\newcommand
does not create a group by itself. You could do\newcommand{\dosomething}{{...}}
.\def
and\newcommand
in the same code is likely to lead to obscure errors clearer to stick to primitive constructs or latex ones, not a mixture of the two.\begingroup
and\endgroup
, imho.\dosomething
you could name the thing\WithinTheCurrentScopeTurnSomethingIntoAnotherThing
. At first glimpse long macro names which have a semantical aspect as they explain what the thing does seem cumbersome. But they can be very nice when the need of debugging arises.\newcommand
/\renewcommand
apply to the current scope. In order to prevent this make sure that another local scope is opened up before the (re)definition-assignments in question are carried out. E.g., by means of\begingroup..\endgroup
or{..}
or\bgroup..\egroup
. In case you wish (re)definitions in terms of\(re)newcommand
to apply to all superordinate scopes also, look at the package letltxmacro, especially the command\GlobalLetLtxMacro
.