如何在每次循環時遞增變量

如何在每次循環時遞增變量

我正在編寫一個宏,它將數字列表作為其唯一參數。當我迭代列表時,我想追蹤列表中項目的索引。這是我想要的一個例子:

% \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}

假裝這\index是獲得我想要的東西的方法,我會將此巨集編寫為:

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

有沒有辦法做到這一點?我知道,如果我想將其稱為\myMacro{2/1,1/2,3/3},我可以將一行替換為\foreach \height/\index in #1 {,但我更願意不需要在參數中傳遞索引。

答案1

pgffor 套件( 的一部分tikzcount為此提供了一個鍵,您可以將其指派給巨集。請注意,您需要在巨集定義中{ }圍繞。#1

\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}

程式碼的輸出

相關內容