# Result of pgmathsetmacro is lost in loop iterations

Consider the following code.

%!TEX program = lualatex
\documentclass[tikz]{standalone}

\begin{document}

\pgfmathsetmacro{\sumk}{0}

\foreach \k in {1,2,...,10}{
\pgfmathsetmacro{\sumk}{\k+\sumk}
\directlua {print(\k,\sumk)}
}

\end{document}


In this simple example, I want to sum recursively from 1 to 10. This is just done to reproduce my problem: accessing a variable which is set within the loop in next loop iteration, and possibly accessing it also after the loop ended.

My expected output would be (in the log, written with lua print)

1   1.0
2   3.0
3   6.0
4   10.0
5   15.0
6   21.0
7   28.0
8   36.0
9   45.0
10  55.0


However, it is

1   1.0
2   2.0
3   3.0
4   4.0
5   5.0
6   6.0
7   7.0
8   8.0
9   9.0
10  10.0


Can a macro defined within the loop be reused later?

Here is a way:

\documentclass[tikz]{standalone}

\begin{document}

\def\sumk{0}
\def\finsumk{0}
\noindent\foreach \k in {1,2,...,10}{%
\pgfmathsetmacro{\sumk}{\k+\finsumk}%
\xdef\finsumk{\sumk}%
%\directlua {print(\k,\sumk)}
\k, \finsumk\\
}

\end{document}


PS: Add the lua code instead of my simple LaTeX way to print.

Reason of your failure: Try to change my \xdef to \def and you will realize that it doesn't work because been lost (gets 0) in every iteration. This is because \sumk is a value that expands for one usage inside the code and \xdef first expands it and then save it globally.

• The explanation helps me to understand it, thanks! Tikz even has some built-in functionality, but your answer seems more general. – Faekynn Aug 23 at 14:56
• Thanks @Faekynn ... Happy TeXing. – koleygr Aug 23 at 15:10

Actually, TikZ/pgf offers a quite simple solution. For me, the standard behavior is completely unexpected.

%!TEX program = lualatex
\documentclass[tikz]{standalone}

\begin{document}

\pgfmathsetmacro{\sumk}{0}

\foreach \k [remember=\sumk as \sumk] in {1,2,...,10}{
\pgfmathsetmacro{\sumk}{\k+\sumk}
\directlua {print(\k,\sumk)}
}

\end{document}


It is actually a common behavior of \foreach compared to e.g. \pgfplotsinvokeforeach provided by pgfplots. You can get more information about this behavior and some examples in pgf-tikz manual § 7 Utilities and pgfplots manual § 8.1 Utility Commands. I think it is because \foreach introduces scopes, while \pgfplotsinvokeforeach does not, so the \sumk variable is not expanded.

The following example produces the desired output

%!TEX program = lualatex
\documentclass[tikz]{standalone}
\usepackage{pgfplots}
\begin{document}

\pgfmathsetmacro{\sumk}{0}

\pgfplotsinvokeforeach{1,2,...,10}{
\pgfmathsetmacro{\sumk}{#1+\sumk}
\directlua {print(#1,\sumk)}
}

\end{document}