# Problem with loop-generated pkgkeys containing a space

I'm trying to use \pgfkeys in the following setting:

\documentclass{article}

\usepackage{tikz}
\usepackage{pgfkeys}

\begin{document}
\begin{tikzpicture}[%
m1 color/.initial=red,
m2 color/.initial=green,
m3 color/.initial=blue,
]
\foreach \i in {1, ..., 3} {%
\pgfkeys{/tikz/m\i color/.get=\c}
\node at (0, \i) [color=\c] {\i};
}
\end{tikzpicture}
\end{document}


And when I compile it, I get the following error:

! Package xcolor Error: Undefined color \c '.


If I change the code to not use \i to select the key, i.e.:

\documentclass{article}

\usepackage{tikz}
\usepackage{pgfkeys}

\begin{document}
\begin{tikzpicture}[%
m1 color/.initial=red,
m2 color/.initial=green,
m3 color/.initial=blue,
]
\foreach \i in {1, ..., 3} {%
\pgfkeys{/tikz/m1 color/.get=\c}
\node at (0, \i) [color=\c] {\i};
}
\end{tikzpicture}
\end{document}


then it compiles, but now I can't iterate over the keys.

I also noticed that this actually works:

\documentclass{article}

\usepackage{tikz}
\usepackage{pgfkeys}

\begin{document}
\begin{tikzpicture}[%
color1/.initial=red,
color2/.initial=green,
color3/.initial=blue,
]
\foreach \i in {1, ..., 3} {%
\pgfkeys{/tikz/color\i/.get=\c}
\node at (0, \i) [color=\c] {\i};
}
\end{tikzpicture}
\end{document}


So what's the problem with the first example?

Just for curiosity, I tried changing m1 color to m1_color, and now it works. Hence, it appears to have something to do with the spaces. But what?

-
pgfkeys is loaded implicitly by tikz package anyway so you don't need to include it externally. –  percusse Mar 29 '12 at 14:38
@percusse: Indeed it is. Thanks. =) –  gablin Mar 29 '12 at 15:41
add comment

## 2 Answers

Macros remove any spaces behind them, so m\i color will be expanded to m1color not m1 color, etc. You need to add an explict space: m\i\space color:

\documentclass{article}

\usepackage{tikz}
\usepackage{pgfkeys}

\begin{document}
\begin{tikzpicture}[%
m1 color/.initial=red,
m2 color/.initial=green,
m3 color/.initial=blue,
]
\foreach \i in {1, ..., 3} {%
\pgfkeys{/tikz/m\i\space color/.get=\c}
\node at (0, \i) [color=\c] {\i};
}
\end{tikzpicture}
\end{document}


Also note that using a macro for a key value is not always supported. In the case of color it is, but for other keys you might want to expand it first by adding /.expand once to the key, like color/.expand once=\c.

-
I suspected that that was the problem, but I wasn't aware of the \space command (I tried using m\i\ color but that didn't work). –  gablin Mar 29 '12 at 15:05
@gablin: The space must be expandable. \  adds a typesetable space which isn't. \space on the other site simply expands to  . –  Martin Scharrer Mar 29 '12 at 15:07
add comment

It compiles without error if you change

\pgfkeys{/tikz/m\i color/.get=\c}


to

\pgfkeys{/tikz/m\i\space color/.get=\c}
`

I can't promise it gets the result you intend though.....

-
add comment