1

I am drawing a picture in my document using a foreach loop in a tikzpicture environment, like this stripped-down example:

\documentclass{standalone}
\usepackage{tikz}

\newcommand{\drawBoxes}[1]{
  \begin{tikzpicture}
    \foreach \y\x\char in {#1}
    {
      \node at (\x*20pt, -\y*20pt) {\char};
    }
  \end{tikzpicture}
}

\begin{document}
\drawBoxes{1/1/a, 1/2/b, 2/1.5/c}
\end{document}

That produces the following result:

Output

In my real document, the text that is used in the foreach loop is coming from an optional command argument that is parsed using pgfkeys, and so I have its value in the form of a macro. When I pass a macro to the \drawBoxes command, though, it doesn't work.

\documentclass{standalone}
\usepackage{tikz}

\newcommand{\drawBoxes}[1]{
  \begin{tikzpicture}
    \foreach \y\x\char in {#1}
    {
      \node at (\x*20pt, -\y*20pt) {\char};
    }
  \end{tikzpicture}
}

\begin{document}
\def \theseBoxes {1/1/a, 1/2/b, 2/1.5/c}
\drawBoxes{\theseBoxes}
\end{document}

produces this error message:

! Package PGF Math Error: Unknown function `a' (in '1/1/a').

See the PGF Math package documentation for explanation. Type H for immediate help. ...

l.15 \drawBoxes{\theseBoxes}

How can I fix this problem?

I see that similar questions have been asked before; so far, however, I am having a difficult time understanding the presented solutions and adapting them to my specific case.

1 Answer 1

1

Drop the braces, \foreach \y\x\char in #1. See the first pair of examples in pgfmanual, sec. 88 "Repeating Things: The Foreach Statement" (unofficial html version).

Also I'm surprised that \foreach \y\x\char in ... works, rather than \foreach \y/\x/\char in ....

3
  • Thanks, that worked! May 11, 2022 at 3:18
  • In the context of my real document, removing the braces around {#1} in the foreach loop results in a different error: Runaway argument? ... ! Paragraph ended before \pgffor@next was complete. It seems that my stripped down example is somehow not truly representative of what's happening in my document. I will have to investigate further. May 11, 2022 at 10:54
  • @SteveEddins Maybe caused by a blank line, which is converted to \par. May 11, 2022 at 12:50

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .