# Update pgfmath macro in foreach loop

I need to update a variable defined in a pgfmathsetmacro command inside a foreach loop. Apparently, the var is only updated when it is used after the update command. Here is a MWE:

\begin{tikzpicture}
\draw [help lines] (0,0) grid (3,3);
\pgfmathsetmacro{\a}{1}
\foreach \b in {2,3} {
\node [blue] at (\a,0) {\a};
\pgfmathsetmacro{\a}{\b}
\node [red] at (0,\a) {\a};
}
\end{tikzpicture}


The red nodes are printed at updated positions and the value printed is also updated; the blue nodes are not: they keep their initial value (1) and are located at the initial position (0,1). Why is this? Thanks José

• These definitions are (luckily) local. – user121799 Jun 9 '18 at 19:25

The \pgfmathsetmacro definitions are only local. You can understand this better by comparing this to \gdef.

\documentclass[tikz,border=3.14mm]{standalone}
\begin{document}
\begin{tikzpicture}
\draw [help lines] (0,0) grid (3,3);
\pgfmathsetmacro{\a}{1}
\foreach \b in {2,3} {
\node [blue] at (\a,0) {\a};
\pgfmathsetmacro{\a}{\b}
\node [red] at (0,\a) {\a};
}
\end{tikzpicture}
\begin{tikzpicture}
\draw [help lines] (0,0) grid (3,3);
\pgfmathsetmacro{\a}{1}
\foreach \b in {2,3} {
\node [blue] at (\a,0) {\a};
\gdef\a{\b}
\node [red] at (0,\a) {\a};
}
\end{tikzpicture}
\end{document}


In the second picture, \a gets redefined globally. Notice that it is intended and advantageous to have these definitions local otherwise you may get in real trouble if you use macro names like \a and \b as you do.

• Oh, I see! \pgfmathsetmacro definitions are local as in "local for each iteration". As such, any invocation of the variable before the redefinition inside the loop uses the initial, global, definition. Thank you very much. – ljmamoreira Jun 9 '18 at 21:12
• @ljmamoreira Yes, precisely. (That's why nice loops like \foreach \phi in {1,2,3} are not necessarily fatal, but it is still better to use different symbols for these local macros because in more complex situations it might be hard to find out what's going on.) – user121799 Jun 9 '18 at 21:35

Option remember can be used to access the previous value of a \foreach variable:

\documentclass[tikz]{standalone}
\begin{document}
\begin{tikzpicture}
\draw [help lines] (0,0) grid (3,3);
\foreach \b [remember=\b as \a (initially 1)] in {2,3} {
\node [blue] at (\a,0) {\a};
\node [red] at (0,\b) {\b};
}
\end{tikzpicture}
\end{document}