讀取命令中的參數?

讀取命令中的參數?

我現在知道,如果我想獲取傳遞給命令的第三個參數,我可以使用 use #3。我的問題是,如果這個參數是一個數組,我如何在沒有 for 迴圈的情況下讀取數組的元素?

例如,當 {1,2,3} 作為第三個參數傳遞。我該如何閱讀它的第二個元素?

注意:假設我總是會得到一個逗號分隔的恆定長度的陣列。

答案1

\documentclass{article}

\def\firstinlist#1,#2,#3\stoplist{#1}
\def\secondinlist#1,#2,#3\stoplist{#2}
\def\thirdinlist#1,#2,#3\stoplist{#3}

\newcommand{\foo}[1]{%
  The list has\\
  \firstinlist#1\stoplist\\
  \secondinlist#1\stoplist\\
  \thirdinlist#1\stoplist}

\begin{document}

\noindent\foo{1,2,3}

\end{document}

在此輸入影像描述


一個更簡單的定義,其中循環由內部巨集執行,是使用xparseLaTeX3

\documentclass{article}
\usepackage{xparse}
\ExplSyntaxOn
\DeclareExpandableDocumentCommand{\getlistitem}{mm}
 {
  \clist_item:nn { #2 } { #1 }
 }
\ExplSyntaxOff

\newcommand{\foo}[1]{%
  The list has\\
  \getlistitem{1}{#1}\\
  \getlistitem{2}{#1}\\
  \getlistitem{3}{#1}}

\begin{document}
\noindent\foo{1,2,3}

\end{document}

答案2

以下可能符合您的要求:

在此輸入影像描述

\documentclass{article}
\usepackage{etoolbox}% http://ctan.org/pkg/etoolbox
\newcounter{itemnum}
\newcommand{\mymacroA}[3]{%
  \setcounter{itemnum}{0}% Start counting from first item
  \gdef\seconditem{\relax}%
  \renewcommand*{\do}[1]{%
    \stepcounter{itemnum}%
    \ifnum\value{itemnum}=2\relax
      \gdef\seconditem{##1}%
    \fi%
  }%
  \docsvlist{#3}%
}
\makeatletter
\def\extractsecond#1,#2,#3{#2}%
\newcommand{\mymacroB}[3]{%
  \gdef\seconditem{\extractsecond#3}%
}
\makeatother
\begin{document}
\mymacroA{a}{b}{1,2,3,4,5}%
\seconditem

\mymacroA{a}{b}{6,1}%
\seconditem

\mymacroA{a}{b}{123}%
\seconditem

\mymacroA{a}{b}{a,\textbf{b},c}%
\seconditem

\mymacroB{a}{b}{1,2,3}%
\seconditem

\mymacroB{a}{b}{6,1,9}%
\seconditem

\mymacroB{a}{b}{a,\textbf{b},c}%
\seconditem

\end{document}

第一個是使用的實現etoolbox的列表處理能力。因此,\mymacroA遍歷給定清單並挑選出第二項,並將其儲存在 中\seconditem

第二個實現假設一個固定列表,該列表類似於<first>,<second>,<third>並根據該固定定義挑選出第二個。之所以有效,是因為您可以指定巨集的參數文本,它應該準確地修補。

相關內容