如何建立一個巨集來建立其他巨集(帶有參數)?

如何建立一個巨集來建立其他巨集(帶有參數)?

我想創建一個宏,即\newpoint{<point name>}{<point style>},它創建像\Point<point name>{<x coord>}{<y coord>}{<label>}.

我見過如何定義一個巨集來建立一個新的巨集,並將名稱作為其參數傳遞?這是一半,因為它沒有顯示如何使建立的巨集接收參數。

我試過:

\newcommand*{\newpoint}[2]{%
   \tikzset{#1/.style={#2}}%
   \newcounter{point#1}\setcounter{point#1}{0}%
   \def\csname Point#1\endcsname (##1,##2)|##3;{%
        \stepcounter{point#1}\fill[#1] (##1,##2) circle (2pt) node[above](#1-\thepoint#1){##3};}%
}

但從表面上看,老實說,它不起作用Use of \csname doesn't match it's definition……我不知道我在做什麼了。

這是我的M()我們:

\documentclass[tikz, border=2mm]{standalone}
\newcommand*{\newpoint}[2]{%
   \tikzset{#1/.style={#2}}%
   \newcounter{point#1}\setcounter{point#1}{0}%
   \def\csname Point#1\endcsname (##1,##2)|##3;{%
        \stepcounter{point#1}\fill[#1] (##1,##2) circle (2pt) node[above](#1-\thepoint#1){##3};}%
}
\newpoint{A}{red}
\begin{document}
 \begin{tikzpicture}
  \PointA(1,2)|A;
 \end{tikzpicture}
\end{document} 

答案1

正如@daleif 所說,\expandafter放在\def.為了得到\thepointA你必須使用\csname ... \endcsname那裡。我想這就是你想要的:

\newcommand*{\newpoint}[2]{%
   \tikzset{#1/.style={#2}}%
   \newcounter{point#1}\setcounter{point#1}{0}%
   \expandafter\def\csname Point#1\endcsname (##1,##2)|##3;{%
        \stepcounter{point#1}\fill[#1] (##1,##2) circle (2pt) node[above](#1-\csname thepoint#1\endcsname){##3};}%
}

這裡有一個解決方案,每次呼叫 時都沒有真正的計數器,基於 @egreg 的偽計數器解決方案,但每次呼叫巨集\newpoint時都會增加偽計數器。\point<name>

\newcounter{pointnumber}
\newcommand\StepPointNumber[1]{%
    \setcounter{pointnumber}{\csname number@point#1\endcsname}%
    \stepcounter{pointnumber}
    \expandafter\xdef\csname number@point#1\endcsname{\thepointnumber}%
              \expandafter\show\csname number@point#1\endcsname
}
\newcommand*{\newpoint}[2]{%
   \tikzset{#1/.style={#2}}%
   \expandafter\def\csname number@point#1\endcsname{0}%
   \expandafter\def\csname Point#1\endcsname (##1,##2)|##3;{%
        \StepPointNumber{#1}%
        \fill[#1] (##1,##2) circle (2pt) node[above](#1-\csname number@point#1\endcsname){##3-\csname number@point#1\endcsname};}%
}

答案2

我認為沒有必要分配一個新的計數器,除非你想用它來進行算術運算。

不過,重點是您需要\csname以正確的方式使用:

\documentclass[tikz, border=2mm]{standalone}

\newcommand*{\newpoint}[2]{%
   \tikzset{#1/.style={#2}}%
   \expandafter\def\csname number@point#1\endcsname{0}%
   \expandafter\def\csname Point#1\endcsname (##1,##2)|##3;{%
        \fill[#1] (##1,##2) circle (2pt) node[above](#1-\csname number@point#1\endcsname){##3};}%
}

\newpoint{A}{red}

\begin{document}

\begin{tikzpicture}
  \PointA(1,2)|A;
\end{tikzpicture}

\end{document}

相關內容