[Tex/LaTex] A reusable newlength (no stop/break if length already defined)

conditionalslengthsmacros

Often I have separate .tikz files, which may contain stuff like \newlength{\mytmplen}; and given I'm not very original with names, the same statement ends up in multiple such files. Which turns out to be a problem, if I want to include all those files in a single .tex document — then upon the second \newlength with the same argument, the compilation process would stop with:

! LaTeX Error: Command \mytmplen already defined.
               Or name \end... illegal, see p.192 of the manual.

See the LaTeX manual or LaTeX Companion for explanation.
Type  H <return>  for immediate help.
 ...                                              

l.30 \newlength{\mytmplen}

? 

So, I thought of devising a new newlength command, which would define the new length if it doesn't exist; but it would simply typeout a message, and go on if it does exist.

Obviously, I'd have to have a method to check if a command exists; and possibly a method to obtain the command name (e.g. mytmplen) from the command token (e.g. \mytmplen). So far, I found these posts relevant:

I will be posting my solution as answer below; of course, corrections or alternative methods for solving this would be much appreciated!

Best Answer

Your answer appears to work. A simpler method might consist of first \let-ting the length variable in question to \relax and then applying \newlength to it. Put differently, if you can't remember if a certain macro name has been used before to denote a length parameter (or anything else, really!) and if you're comfortable with (re)using it anyway, you can first \let it to \relax and then issue a \newlength directive.

\documentclass{article}
\begin{document}

\newlength\mytmplen
\setlength\mytmplen{10pt}
\the\mytmplen

\let\mytmplen\relax % let \mytmplen to \relax

\newlength\mytmplen % now it's safe to "re-issue" it as a length 
\setlength\mytmplen{20pt}
\the\mytmplen

\end{document}

enter image description here

Related Question