[Tex/LaTex] Newline is not working with parbox and usebox

boxesline-breakingmacros

I would like to save data to a savebox (or any other storage element) in iterations. At the end I would like to put each datapoint in a framebox and then in a frambox container with a given width.
Here is my implementation:

\documentclass{article}

\newsavebox{\foo}
\newcommand{\savedata}[1]{\savebox{\foo}{\usebox{\foo} \fbox{#1}}}
\newcommand{\printdata}{\framebox{\parbox{4cm}{\usebox{\foo}}}}
\begin{document}
The desired usage:
\savedata{This is a box}
\savedata{This is another box}
\savedata{This is third box}
\printdata
\\
The desired output:
\framebox{\parbox{4cm}{
  \fbox{This is a box} 
  \fbox{This is another box} 
  \fbox{This is third box}}}
\end{document}

Output:
Output
As seen does the container not wrap the inner framebox when using the programmatic implementation. What is wrong?

Best Answer

You want raggedright to allow the lines to be short and need to unbox the saved data to allow linebreaking:

\documentclass{article}

\newsavebox{\foo}
\newcommand{\savedata}[1]{\savebox{\foo}{\ifvoid\foo\else\unhbox\foo{} \fi\fbox{#1}}}
\newcommand{\printdata}{\framebox{\parbox{4cm}{\raggedright\unhbox\foo}}}
\begin{document}
The desired usage:
\savedata{This is a box}
\savedata{This is another box}
\printdata

The desired output:
\framebox{\parbox{4cm}{\raggedright\fbox{This is a box} \fbox{This is another box}}}
\end{document}