2

I'm attempting to nest commands in my TikZ pages so that I can make progressively more complicated things with small bits of code at each level. The code I have so far is

\documentclass{article}
\usepackage{tkz-graph}

\newcommand{\drawSquare}[3]{%
  \draw[thick,#3] (#1-0.5,#2-0.5) rectangle (#1+0.5,#2+0.5);}
\newcommand{\boxesAtHeight}[3]{%
  \foreach \i in {1,...,#1}
    \drawSquare{\i}{#2}{#3}}

\begin{document}

\begin{tikzpicture}
  \boxesAtHeight{4}{0}{black}
  \boxesAtHeight{2}{1}{black}
  \boxesAtHeight{1}{2}{black}
\end{tikzpicture}

\end{document}

I use sharelatex, and when I try to compile, I get 4 errors. On the line after \end{tikzpicture}, I have the error

Paragraph ended before \pgffor@next was complete.

On the line of \end{document}, I get the three errors

Missing \endgroup inserted.

Missing } inserted.

LaTeX error: \begin{tikzpicture} on input line 12 ended by \end{document}.

When I replace the code within the tikzpicture by expanding the \boxesAtHeight macro, I get the same errors.

When I further expand the \drawSquare macro, I get the following output

successful output after expanding every macro

To be clear, the first expansion resulted in the code

\begin{tikzpicture}
  \foreach \i in {1,...,4}
    \drawSquare{\i}{0}{black}
  \foreach \i in {1,...,2}
    \drawSquare{\i}{1}{black}
  \foreach \i in {1,...,1}
    \drawSquare{\i}{2}{black}
\end{tikzpicture}

And the second expansion resulted in the code

\begin{tikzpicture}
  \foreach \i in {1,...,4}
    \draw[thick,black] (\i-0.5,0-0.5) rectangle (\i+0.5,0+0.5);
  \foreach \i in {1,...,2}
    \draw[thick,black] (\i-0.5,1-0.5) rectangle (\i+0.5,1+0.5);
  \foreach \i in {1,...,1}
    \draw[thick,black] (\i-0.5,2-0.5) rectangle (\i+0.5,2+0.5);
\end{tikzpicture}

Can anyone explain to me why I'm getting errors? I know that the \drawSquare macro works outside of loops.

2
  • Welcome to TeX.SX! It looks like you are drawing Young tableaux, if so, have you had a look at ytableau?
    – JP-Ellis
    Commented Feb 19, 2016 at 1:20
  • @JP-Ellis, I believe ytableau will work for this particular project, thanks! I'll use ytableau for this project, but I also hope someone can answer my question so I can have it work in the future when I'm making other things.
    – Pi Fisher
    Commented Feb 19, 2016 at 1:31

1 Answer 1

2

You need to group the body of the for loop:

\documentclass{article}
\usepackage{tkz-graph}

\newcommand{\drawSquare}[3]{%
  \draw[thick,#3] (#1-0.5,#2-0.5) rectangle (#1+0.5,#2+0.5);}
\newcommand{\boxesAtHeight}[3]{%
  \foreach \i in {1,...,#1}
    {\drawSquare{\i}{#2}{#3}}}%<== put the \drawSquare{\i}{#2}{#3} in {}

\begin{document}

\begin{tikzpicture}
  \boxesAtHeight{4}{0}{black}
  \boxesAtHeight{2}{1}{black}
  \boxesAtHeight{1}{2}{black}
\end{tikzpicture}

\end{document}

result

0

You must log in to answer this question.

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