10

Consider the following example (I edited the example to include LaTeX lrbox environment):

\documentclass{beamer}
\newsavebox\mybox
\newsavebox\myboxb

\begin{document}
\frame{
  \sbox\mybox{Hello World!}\usebox\mybox %works

  \begin{lrbox}\myboxb Bonjour!\end{lrbox}\usebox\myboxb %works
}

\frame{
  \usebox\mybox %is empty

  \usebox\myboxb %is empty
}
\end{document}

Why is it that the second frame is blank? Is there possibly a workaround?

lockstep
  • 250,273
AlexG
  • 54,894

2 Answers2

12

Use \global, to let \sbox have global effect. Otherwise it's local, within the scope of the frame environment.

\begin{frame}
  \global\sbox\mybox{Hello World!}
  \usebox\mybox
\end{frame}
Stefan Kottwitz
  • 231,401
  • Well, not quite satisfied. I actually want to use \begin{lrbox}\mybox ...\end{lrbox}. What can I do here to make the assignment global? – AlexG Feb 01 '12 at 11:16
  • @AlexanderGrahn: Perhaps post this actual problem with lrbox with a new example as another question, since it seems to be different. – Stefan Kottwitz Feb 01 '12 at 11:23
  • @AlexanderGrahn: You could use \global\setbox\mybox=\box\mybox after the lrbox environment to make the assignment global. – Martin Scharrer Feb 01 '12 at 12:19
  • @MartinScharrer: Thanks! I like the idea of globally overwriting the box register content with itself. So redefining \setbox into a global command, as proposed by egreg, is not necessary. Could you add this as a separate answer? – AlexG Feb 01 '12 at 15:40
7

You can use \global\sbox (but \global\savebox won't work); for a "global" lrbox you can define your own environment:

\usepackage{etoolbox}
\cslet{lrbox*}\lrbox
\expandafter\patchcmd\csname lrbox*\endcsname{\setbox}{\global\setbox}{}{}
%\expandafter\show\csname lrbox*\endcsname % uncomment to see if it has worked
\cslet{endlrbox*}\endlrbox

Now

\begin{lrbox*}{\mybox}
Hello world!
\end{lrbox*}

will set globally the contents of \mybox.

egreg
  • 1,121,712
  • Why can't you create another box, say \myotherbox and then do something like \global\savebox\myotherbox{\usebox{\mybox}} before exiting the environment? – A.Ellett Jul 09 '13 at 16:17
  • @A.Ellett Because you can't use \global in front of \savebox; one could do with \global\sbox, but this adds a level of boxing. – egreg Jul 09 '13 at 16:19