Strange behaviour of foreach

Ulrich has already provided you with a nice fix that works for straight connections. The question is what goes wrong. The issue is that the parser wants to see an explicit ( (or an option etc.) but not a macro that expands to something starting with a ( after a to. So one way to fix this here is to expand the macros first and then "activate" the \draw command.

\documentclass{standalone}
\usepackage{tikz}

\begin{document}

\begin{tikzpicture}

\foreach \a / \b in {
(20:1) / (90:1)
,(-20:1) / (-90:2)
}
{
\node at \a {$\a$};
\node at \b {$\b$};
\edef\temp{\noexpand\draw \a to \b;}
\temp
}
\end{tikzpicture}

\end{document}

enter image description here

Of course, there are many variations possible, e.g.

 \edef\temp{ to \b}
 \draw \a \temp;

or a more TikZy version

 \draw [insert path/.expanded={\a to \b}];

Alternatively, you could give TikZ the explicit parentheses.

\documentclass{standalone}
\usepackage{tikz}

\begin{document}

\begin{tikzpicture}

\foreach \a/\b in {
20:1/90:1,%
-20:1/-90:2%
}
{
\node at (\a) {$(\a)$};
\node at (\b) {$(\b)$};
\draw (\a) to (\b);
}
\end{tikzpicture}

\end{document}

Anyway, the connections become much nicer if you name the nodes, in which case the problem does not arise.

\documentclass{standalone}
\usepackage{tikz}

\begin{document}

\begin{tikzpicture}

\foreach \a / \b in {
(20:1) / (90:1)
,(-20:1) / (-90:2)
}
{
\node (a) at \a {$\a$};
\node (b) at \b {$\b$};
\draw (a) to (b);
}
\end{tikzpicture}

\end{document}

enter image description here


When I write \draw \a -- \b; instead of \draw \a to \b;, then everything seems to work out.

When I write \draw \a \expandafter t\expandafter o\b; instead of \draw \a to \b;, then everything seems to work out, too.

Seems after to expandable tokens like \b don't get expanded before evaluating the composition of to's operands.

I can offer a macro \SecondArgumentsFirstTokenTopLevelExpanded which can be used for having \b toplevel-expanded before the to-operator is encountered:

\documentclass{standalone}

\newcommand\exchange[2]{#2#1}%
\newcommand\SecondArgumentsFirstTokenTopLevelExpanded[2]{%
  \expandafter\exchange\expandafter{#2}{#1}%
}%

\usepackage{tikz}

\begin{document}

\begin{tikzpicture}
\foreach \a / \b in {(20:1)/(90:1),(-20:1)/(-90:2)}{
  \node at \a {$\a$};
  \node at \b {$\b$};
  \draw \a \SecondArgumentsFirstTokenTopLevelExpanded{to}{\b};
}
\end{tikzpicture}

\end{document}