Take the 2-minute tour ×
TeX - LaTeX Stack Exchange is a question and answer site for users of TeX, LaTeX, ConTeXt, and related typesetting systems. It's 100% free, no registration required.

I have a small problem with the TikZ \foreach loop whenever the list, over which we loop, is defined my a macro. The following code example will show my problem:

\documentclass{scrartcl}
\usepackage[utf8]{inputenc}
\usepackage{tikz}

\begin{document}
Picture one:

\begin{tikzpicture}
\foreach \x/\y in {1.0/2.0, 3.0/4.0} \node[draw] at (\x,\y) {\x--\y};
\end{tikzpicture}

Picture two:

\newcommand{\mymacro}{1.0/2.0, 3.0/4.0}
\begin{tikzpicture}
\foreach \x/\y in {\mymacro} \node[draw] at (\x,\y) {\x--\y};
\end{tikzpicture}
\end{document}

The expected result is that both images should look the same. But in the second image, I only get one node - and both \x and \y are each time expanded to 1.0/2.0, 3.0/4.0. I hope someone can help.

share|improve this question
    
Welcome to tex.sx! Note that it is unusual around here to have any greeting. –  lockstep Feb 25 '11 at 22:13

1 Answer 1

up vote 19 down vote accepted

The \mymacro isn't expanded by the \foreach loop, but only afterwards. You need to remove the braces { } around the macro to make it work:

\documentclass{scrartcl}
\usepackage[utf8]{inputenc}
\usepackage{tikz}

\begin{document}
Picture one:

\begin{tikzpicture}
\foreach \x/\y in {1.0/2.0, 3.0/4.0} \node[draw] at (\x,\y) {\x--\y};
\end{tikzpicture}

Picture two:

\newcommand{\mymacro}{1.0/2.0, 3.0/4.0}
\begin{tikzpicture}
\foreach \x/\y in \mymacro \node[draw] at (\x,\y) {\x--\y};
\end{tikzpicture}
\end{document}

Note that while normally both arguments {\mymacro} and \mymacro are identical, \foreach seems to test for { and expands the argument if it isn't present.

share|improve this answer
    
Thanks, that's a pausible explanation. –  slouwrun Feb 25 '11 at 22:19
    
@slouwrun: As far as I remember this is an explicit feature of the \foreach macro. –  Martin Scharrer Feb 25 '11 at 22:21
2  
Good! I deleted my shorter answer. Btw. the pgf manual says: Still in the easiest case, <list> is either a comma-separated list of values surrounded by curly braces or it is the name of a macro that contain such a list of values. –  Stefan Kottwitz Feb 25 '11 at 22:43

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.