Use a variable in foreach

foreachloopspgfmathvariable

I am trying to use a variable in my foreach loop. It would make things a lot easier, because i only need to change one value and multiple loops are affected.

Something like this:

\begin{tikzpicture}[y=-1cm]
    
    \pgfmathsetmacro\end{2}

    \foreach \x in {0,...,\end}{
        %do something
    }


    \foreach \x in {1,...,\end}{
        %do something
    }

\end{tikzpicture}

The problem is that when using this im getting lots of errors that aren't related to this tikZ image. There mostly Something's wrong--perhaps a missing \item. Like something broke.

Thanks a lot in advantage

Best Answer

You're redefining \end at the same grouping level as the \end{tikzpicture} instruction. So when TeX sees \end{tikzpicture} it will obey your redefinition and replace it with

2.0{tikzpicture}

Can you see why your choice isn't really good?

Use a different name, there's plenty of them, for instance \END. But it should really be

\pgfmathtruncatemacro{\END}{2}

otherwise you will get 2.0 and the loop would use floating point numbers.

Example:

\documentclass{article}
\usepackage{tikz}

\begin{document}

\begin{tikzpicture}
  \pgfmathtruncatemacro\END{2}
  \foreach \x in {0,...,\END}{
       \draw(\x,1)--(\x,0);
  }
\end{tikzpicture}

\end{document}