# lrbox doesn't work in math mode

I'm trying to create a custom environment, using which I'd be able to create a box around a certain part of an equation in math mode. I have tried to use lrbox to make it possible to use fbox. Unfortunately using lrbox causes strange errors about various missing symbols (removing the fbox part results in exactly the same errors).

MWE:

% !TeX program = xelatex
\documentclass{article}

\usepackage{mathtools}

% For important formulas
\newsavebox{\formulabox}
\newenvironment{formula}{\begin{lrbox}{\formulabox}}{\end{lrbox}\fbox{\usebox{\formulabox}}}

\begin{document}
\begin{displaymath}
\left.
\begin{array}{lcl}
q & \sim & t\\
q & \sim & I
\end{array}
\right\}
\implies
\begin{formula}
I=\frac{q}{t}
\end{formula}
\end{displaymath}
\end{document}


Errors (explanations for insertions removed for brevity):

! Missing $inserted. <inserted text>$
l.20 ^^I^^I^^II=\frac{q}{t}

! Extra }, or forgotten $. \frac #1#2->{\begingroup #1\endgroup \@@over #2} l.20 ^^I^^I^^II=\frac{q}{t} ! Missing$ inserted.
<inserted text>
$l.21 ^^I^^I\end{formula} ! Missing } inserted. <inserted text> } l.21 ^^I^^I\end{formula}  Mockup of desired result: What am I doing wrong? How can I fix it? • lrbox is like \mbox and sets its content in text mode so you need $ to get back to math, but simpler is to use the \boxed command from amsmath May 17, 2018 at 18:43

lrbox is like \mbox and sets its content in text mode so you need \$ to get back to math, but it's simpler to use the \boxed command from amsmath (which is loaded by mathtools).

\documentclass{article}

\usepackage{mathtools}

\begin{document}
\begin{displaymath}
\left.
\begin{array}{lcl}
q & \sim & t\\
q & \sim & I
\end{array}
\right\}
\implies
\boxed{
I=\frac{q}{t}
}
\end{displaymath}
\end{document}

• @tambre it doesn't matter, but why did you change the image? the one I posted looked more or less the same and was generated by the posted code? May 18, 2018 at 6:40
• I didn't change the image. I only added alt text for it, so people with screenreaders know what's on the picture. May 18, 2018 at 12:04