6

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.

1
  • 1
    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.
    – Alan Munn
    Commented Jul 12, 2017 at 17:19

1 Answer 1

9

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}

output of code

You must log in to answer this question.

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