# Creating a separated table

I'd like to be able to setup a bunch of things to put in a table after gathering them up before hand. Something like the following where I keep a variable with the contents that will eventually be inserted into the document. This technique seems to work fine until I start adding the table stuff like "&" and "\".

\documentclass{article}

\def\mytable{}
\newcommand{\myitem}[2]{
\edef\mytable{\mytable #1 & #2 \\ }
}

\begin{document}

\myitem{foo}{bar}
\myitem{foo}{bar}

\begin{tabular}{cc}
\mytable
\end{tabular}

\end{document}

I'm getting this error

! Undefined control sequence.
\\  ->\let \reserved@e
\relax \let \reserved@f \relax \@ifstar {\let \reserv...
l.10 \myitem{foo}{bar}

?

Don't use \edef for this: many LaTeX commands do not survive it. Rather

\makeatletter
\newcommand{\myitem}{%
}
\makeatother

There are several other techniques, if you don't want the addition to be global, which \g@addto@macro does.

\usepackage{etoolbox}

\newcommand{\myitem}[2]{%
\appto\mytable{#1 & #2 \\}%
}

will do the addition obeying the standard scoping rules.

This seems to work, although using \g@addto@macro seems more reasonable.

\documentclass{article}

\def\mytable{}
\makeatletter
\newcommand{\myitem}[2]{%
\protected@edef\mytable{\mytable #1 & #2 \\}%
}
\makeatother

\begin{document}

\myitem{\textbf{foo}}{bar}
\myitem{one}{two}
\begin{tabular}{cc}
\mytable
\end{tabular}

\end{document}
• \chardef has nothing to do with this: you could just say \let\\=\relax. Also note that & is already unexpandable.
– GuM
Jun 17 '16 at 23:23
• & has no problem whatsoever in \edef. You're just making \\ unexpandable during the \edef; but the problem doesn't vanish: try \myitem{\textbf{a}}{b} Jun 17 '16 at 23:25
• @egreg - So the trick is to make everything unexpandable? Jun 17 '16 at 23:55
• @JohnKormylo The trick is expanding nothing, except \mytable, but just one level. Jun 18 '16 at 6:42