将字符串数组传递给 DeclareNewCommand

将字符串数组传递给 DeclareNewCommand

我需要将字符串数组作为键值(或命名值)传递给命令。我的代码是:

\documentclass{article}
\usepackage{tikz}
\usepackage{xparse}
\usepackage{keyval}
\usepackage{tikz-uml}
\usepackage{pgfmath}

\makeatletter
% ========= KEY DEFINITIONS =========
\define@key{myCommandKeys}{array}{\def\mm@array{#1}}
\DeclareDocumentCommand{\myCommand}{m}
{%
  \begingroup%
      % ========= KEY DEFAULTS + new ones =========
      \setkeys{myCommandKeys}{array={{nothing,to,see,here}},#1}%

      \def\array{\mm@array}

      \pgfmathparse{dim(\array)}
      \edef\arraylength{\pgfmathresult}

      \pgfmathparse{int(\arraylength-1)}
      \edef\lastIndex{\pgfmathresult}

      \node at (0, 5) {array passed: \array};
      \node at (0, 4) {number of items: \arraylength};
      \node at (0, 3) {last index: \lastIndex};

      \foreach \i in {0,...,\lastIndex} {
            \node at (0,1-\i) {item at index \i: \array[\i]};
      }       
  \endgroup%
}
\makeatother

\begin{document}
\begin{tikzpicture}
    \myCommand{array={why,you,no,working!?}}
\end{tikzpicture}
\end{document}

我现在得到的输出是:

在此处输入图片描述

我得到的错误是

Package PGF Math Error: Unknown function `why' (in 'dim(why,you,no,working!?)').

显然,数组长度应该是 4,最后一个索引应该是 3,显示的项目(每行输出一个)应该是:

why 
you
no
working!?

答案1

您必须用 包围数组元素,以"告诉 pgf 它们是字符串而不是函数名称。以下方法有效:

\documentclass{article}
\usepackage{tikz}
\usepackage{xparse}
\usepackage{keyval}
\usepackage{tikz-uml}
\usepackage{pgfmath}

\makeatletter
% ========= KEY DEFINITIONS =========
\define@key{myCommandKeys}{array}{\def\mm@array{#1}}
\DeclareDocumentCommand{\myCommand}{m}
{%
  \begingroup%
      % ========= KEY DEFAULTS + new ones =========
      \setkeys{myCommandKeys}{array={{nothing,to,see,here}},#1}%

      \def\array{{\mm@array}}

      \pgfmathparse{dim(\array)}
      \edef\arraylength{\pgfmathresult}

      \pgfmathparse{int(\arraylength-1)}
      \edef\lastIndex{\pgfmathresult}

      \node at (0, 5) {array passed: \array};
      \node at (0, 4) {number of items: \arraylength};
      \node at (0, 3) {last index: \lastIndex};

      \foreach \i in {0,...,\lastIndex} {
        \node at (0,1-\i) {item at index \i:
          \pgfmathparse{\array[\i]}\pgfmathresult};
      }       
  \endgroup%
}
\makeatother

\begin{document}
\begin{tikzpicture}
    \myCommand{array={"why","you","no","working!?"}}
\end{tikzpicture}
\end{document}

相关内容