pgf-tikz / pgf

A Portable Graphic Format for TeX
https://pgf-tikz.github.io/
1.12k stars 106 forks source link

Error of foreach and node commands #1313

Closed psparkmath closed 6 months ago

psparkmath commented 6 months ago

Brief outline of the bug

I found that foreach command does not work well for \node.

I wrote the code \draw (P1) foreach \n in {2,3}{ -- (P\i) }; to draw lines connecting nodes P1, P2, P3, consecutively. But, this code draw lines connecting P1 and P2 and connecting P1 and P3.

If you change \node part to \coordinate, then foreach command works well.

Minimal working example (MWE)


\documentclass{article}
\usepackage{tikz}

\begin{document}
\begin{tikzpicture}
\foreach[count=\i] \n in {1,3,2}{
    \node (P\i) at (\i,\n) {P\i};
%   \coordinate (P\i) at (\i,\n);
%   \node at (P\i) {P\i};
}
%\draw (P1) -- (P2) -- (P3);
\draw (P1) foreach \i in {2,3}{ -- (P\i)}; % <--- HERE!
\end{tikzpicture}
\end{document}
jasperhabicht commented 6 months ago

This is actually well-known. See, for example: https://tex.stackexchange.com/a/75152/47927

hmenke commented 6 months ago

As documented.

image

There is an undocumented option foreach[scope iterations=false] but it's undocumented for a reason, namely that in most of the cases it's broken.

muzimuzhi commented 6 months ago

Would be fixed by #1304 too?

hmenke commented 6 months ago

Yes. It's also a duplicate of https://github.com/pgf-tikz/pgf/issues/356 and https://github.com/pgf-tikz/pgf/issues/1303 and closely related to https://github.com/pgf-tikz/pgf/issues/1047.