Problem when applying foreach loop
In the \foreach
variant, you are in a group when setting the dimension, so the "outside" value won't change. So you need to make the dimension global (or smuggle it out of the group). Here I made it global by just adding \global
before \xmin=\x
.
\documentclass[tikz]{standalone}
\usetikzlibrary{positioning}
\newdimen\x
\newdimen\xmin
\xmin=10000pt
\newdimen\y
\begin{document}
\begin{tikzpicture}[every node/.style={draw}]
\node (1) {182};
\node[below=of 1] (2) {183731468};
\node[below=of 2] (3) {74632};
\foreach \i in {1,2,3} {
\path (\i.west); \pgfgetlastxy{\x}{\y}
\ifdim\x<\xmin \global\xmin=\x \fi
\fill[red] (\xmin,\y) circle (1pt);
}
\end{tikzpicture}
\end{document}
ADDENDUM: Of course, there are loops which do not introduce groups. The arguably simplest of those is the built-in \loop
.
\documentclass[tikz]{standalone}
\usetikzlibrary{positioning}
\newdimen\x
\newdimen\xmin
\xmin=10000pt
\newdimen\y
\newcounter{loopi}
\begin{document}
\begin{tikzpicture}[every node/.style={draw}]
\node (1) {182};
\node[below=of 1] (2) {183731468};
\node[below=of 2] (3) {74632};
\setcounter{loopi}{0}
\loop
\stepcounter{loopi}
\path (\number\value{loopi}.west); \pgfgetlastxy{\x}{\y}
\ifdim\x<\xmin \xmin=\x \fi
\fill[red] (\xmin,\y) circle (1pt);
\ifnum\number\value{loopi}<3\repeat
\end{tikzpicture}
\end{document}
You can use a different loop that doesn't do grouping. Instead of \i
you use simply #1
.
\documentclass[border=4]{standalone}
\usepackage{xparse}
\usepackage{tikz}
\usetikzlibrary{positioning}
\ExplSyntaxOn
\NewDocumentCommand{\nforeach}{mmm}
{
\cs_set:Nn \joulev_nforeach:n { #3 }
\int_step_function:nnN { #1 } { #2 } \joulev_nforeach:n
}
\ExplSyntaxOff
\newdimen\x
\newdimen\xmin
\newdimen\y
\begin{document}
\begin{tikzpicture}[every node/.style={draw}]
\xmin=10000pt
\node (1) {182};
\node[below=of 1] (2) {183731468};
\node[below=of 2] (3) {74632};
\nforeach{1}{3}{
\path (#1.west); \pgfgetlastxy{\x}{\y}
\ifdim\x<\xmin \xmin=\x \fi
\fill[red] (\xmin,\y) circle (1pt);
}
\end{tikzpicture}
\end{document}