# How to increment a variable each time through a loop

I'm writing a macro that takes a list of numbers as its only parameter. When I iterate through the list, I'd like to keep track of the index of the item in the list. Here's an example of what I want:

% \myMacro{2,1,3} \\ % this is the same as what follows

\begin{tikzpicture}
\draw (1,0) -- +(0,2);
\draw (2,0) -- +(0,1);
\draw (3,0) -- +(0,3);
\end{tikzpicture}


Pretending that \index is the way to get what I want, I'd write this macro as:

\newcommand{\mymacro}[1]%
{\begin{tikzpicture}
\foreach \height in #1 {
\draw (\index,0) -- +(0,\height);
}
\end{tikzpicture}}


Is there a way to do this? I know that, if I wanted to call it as \myMacro{2/1,1/2,3/3}, I could replace one line with \foreach \height/\index in #1 {, but I'd much prefer to not need to pass the indicies in the parameter.

• For future, please don't post code fragments, but instead put the fragment into a minimal compilable document (even if it gives an error) like I did in my answer. Jul 12, 2017 at 17:19

The pgffor package (part of tikz) provides a count key for this which you can assign to a macro. Note that you need { } around the #1 in your macro definition.

\documentclass{article}
\usepackage{tikz}
\newcommand{\mymacro}[1]%
{\begin{tikzpicture}
\foreach \height [count=\myindex] in {#1} {
\draw (\myindex,0) -- +(0,\height);
}
\end{tikzpicture}}
\begin{document}
\mymacro{2,1,3}
\end{document}