Building upon what I was doing in this thread, why didn't my \xdef work?
The Exercise Page comes out just fine. Ideally, the Answer Page would look identical, except, of course with the answers there.
But the Answers Page is gobbledygook. And sometimes it compiles and sometimes it doesn't.
The code works perfectly if I comment out the \AnswerList near the bottom. So the problem is related to that.
What gives?
Here's the code.
\documentclass{article}
\usepackage[margin=2cm]{geometry}
\usepackage{ifthen}
\usepackage{pgf}
\usepackage{pgffor}
\usepackage{tikz}
\setlength{\parindent}{0pt}
\pgfmathsetseed{\number\pdfrandomseed}
\newcommand{\InitVariables}
{
\pgfmathsetmacro{\FactorA}{int(random(1,9))}
\pgfmathsetmacro{\FactorB}{int(random(1,9))}
\pgfmathsetmacro{\Product}{int(\FactorA*\FactorB)}
\pgfmathsetmacro{\Structure}{int(random(0,2))}
}
\newcommand{\AnswerSpace}
{%
\tikz[baseline=6pt]{\draw (0,0)rectangle(0.9,0.9);}
}
\newcommand{\ASF}[1] % Answer Space Filled
{%
\tikz[baseline=6pt]{\draw (0,0)rectangle(0.9,0.9); \node[center] at (0.45,0.35) {\color{blue}#1};}
}
\newcommand{\OneEquation}
{%
\large
\InitVariables
\ifcase\Structure\relax
\def\Exercise{\(\FactorA \times \FactorB = \AnswerSpace\)}
\def\Answer{\(\FactorA \times \FactorB =\ASF{\Product}\)}
\or
\def\Exercise{\(\FactorA \times \AnswerSpace = \Product\)}
\def\Answer{{\(\FactorA \times \ASF{\FactorB} = \Product\)}}
\or
\def\Exercise{\(\AnswerSpace \times \FactorB = \Product\)}
\def\Answer{\(\ASF{\FactorA} \times \FactorB = \Product\)}
\fi
}
\newcommand{\AnswerList}{}
\newcommand{\ExerciseList}[1]
{%
\foreach \x in {1,2,3,...,{#1}}
{%
\OneEquation \Exercise \par \vspace{0.5cm}
\xdef\AnswerList{\AnswerList \Answer \par \vspace{0.5cm}}
}
}
\begin{document}
\section{Exercises}
\ExerciseList{10}
\pagebreak
\section{Answers}
\AnswerList
\end{document}


\vspacecannot be used in\xdef, but it's the simplest. – egreg Oct 07 '16 at 22:59\noexpand\vspacesolves the problem. Or\protected@xdefrather than\xdef. Also, there's a problem with\Answerand the previous contents of\AnswerList. You should define with\protected\defmacros that you don't want to expand inside\(x|e)def(you can look atetoolboxfor more flexibility). Also, is there a real reason to use\pgfmathsetseed{\number\pdfrandomseed}rather than\pgfmathsetseed{3324}(or whatever fixed number that you get randomly in any generator?). – Manuel Oct 07 '16 at 23:03pgfmathsetseed{\number\pdfrandomseed}is code that I've copy/pasted but do not understand. – WeCanLearnAnything Oct 07 '16 at 23:12