[Tex/LaTex] Reuse of \newsavebox and avoiding compilation warnings

boxes

The answer here may be obvious but I can't find it. I use \newsavebox in many routines and for different purposes. These are saved globally and I guess are a reasonably precious resource.

In all instances the box is used for a variety of purposes immediately after content is saved in the box. I don't care about overwriting previous box content (which can be large).

I decided, to save resources to use the same box for many different things

\newsavebox{\mybox}

I don't know in advance which particular routines I am going to need for a particular document, and I don't want to declare a common box outside of the source for each box use. Consequently there are several declarations of \newsavebox{\mybox} (or none at all depending what I am doing).

Bottom line, how can I test for the existence of \mybox before re-creating it? MWE is:

\documentclass{article}
\newsavebox{\mybox}
\newsavebox{\mybox}
\begin{document}
\end{document}

Best Answer

A box defined defined with \newsavebox is basically nothing else than a wrapper command name for the corresponding box register. Checking for the macro name would do, e.g. with \@ifundefined.

\documentclass{article}
\newsavebox{\mybox}

\makeatletter
\@ifundefined{mybox}{%
  \newsavebox{\mybox}%
}{}
\makeatother


\begin{document}
Foo
\end{document}
Related Question