宏 foreach 和语法“...”的问题

宏 foreach 和语法“...”的问题

我已经有几年没有编程了,现在想重新开始工作,但我对“pgf”的更新有些问题(也许……)我对“……”的语法有些问题,以前我并不知道。我安装了最新版本的 texlive、pgf 等……

\documentclass{article}
\makeatletter
\def\DrawPolygon(#1,#2){%
 \begingroup
 \draw(#1)
     \foreach \pt in {#2}{--(\pt)}--cycle;%
 \endgroup
} 
\makeatother

\usepackage{tikz}


\begin{document}
\begin{tikzpicture}
    \coordinate (A) at (4,0);
    \coordinate (B) at (2,4);
    \coordinate (C) at (0,0);   
   % \DrawPolygon(A,...,C) % error 
    % now error undefined\ifpgffor@alphabeticsequence \else \ifpgffor@assign@parse \begingroup
    % ! File ended while scanning use of \pgffor@@dotscharcheck.
    \DrawPolygon(A,B,C)
\end{tikzpicture}
\end{document}

语法(A,...,C)错误

答案1

不要摄入过多的 TiZish,但是,嘿,它有效!

\documentclass{article}
\usepackage{tikz}

\def\DrawPolygon(#1){%
  \begingroup
  \xdef\temppolygon{}%
  \foreach \pt in {#1}{\xdef\temppolygon{\temppolygon(\pt)--}}%
  \xdef\temppolygon{\endgroup\noexpand\draw\temppolygon cycle}%
  \temppolygon;
}

\begin{document}
\begin{tikzpicture}
    \coordinate (A) at (4,0);
    \coordinate (B) at (2,4);
    \coordinate (C) at (0,0);
    \DrawPolygon(A,...,C) % error
\end{tikzpicture}
\end{document}

在此处输入图片描述

答案2

(我将示例从 A、B、C 改为 A、...、E,以使某些观点更加清晰)

我认为问题在于,DrawPolygon(A,...,E)(即A:)的第一个参数被消耗,然后第二个参数(#2)被扩展为(,...,E)而不是所需的A,...,E

解决这个问题的方法是传递起点以及从第二个或结束(DrawPolygon(A,B,...,E)开始的列表,或者通过修改函数的定义,如下所示:

\documentclass{article}
\makeatletter
\def\DrawPolygon(#1,#2){%
 \begingroup
 \draw(#1)
     % change is in this line, {#1,#2} instead of {#2}
     \foreach \pt in {#1,#2}{--(\pt)}--cycle;
 \endgroup
} 
\makeatother
\usepackage{tikz}
\begin{document}
\begin{tikzpicture}
    \coordinate (A) at (4,4);
    \coordinate (B) at (0,4);
    \coordinate (C) at (0,0);   
    \coordinate (D) at (4,0);   
    \coordinate (E) at (7,0);   
    \DrawPolygon(A,...,E)
\end{tikzpicture}
\end{document}

答案3

\foreach确实有循环计数器。可以使用选项 将其分配给宏count。然后可以在第二轮及以后的循环中设置连接线。

\documentclass{article}
\usepackage{tikz}

\def\DrawPolygon(#1){%
  \draw
    \foreach[count=\pti] \pt in {#1} {
      \ifnum\pti>1 --\fi
      (\pt)
    }
    -- cycle
  ;
}

\begin{document}
\begin{tikzpicture}
    \coordinate (A) at (4,4);
    \coordinate (B) at (0,4);
    \coordinate (C) at (0,0);
    \coordinate (D) at (4,0);
    \coordinate (E) at (7,0);
    \DrawPolygon(A,...,E)
\end{tikzpicture}
\end{document}

相关内容