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?

1
  • 2
    Would it be an option to put \sbox\mybox{Hello World!} into the preamble? Would also have global effect. Feb 1, 2012 at 10:58

2 Answers 2

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}
4
  • 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 1, 2012 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 1, 2012 at 11:23
  • @AlexanderGrahn: You could use \global\setbox\mybox=\box\mybox after the lrbox environment to make the assignment global. Feb 1, 2012 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 1, 2012 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.

2
  • 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 9, 2013 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 9, 2013 at 16:19

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .