# Functions defines with a loop (\foreach) makes the tikz picture go far away

In the following MWE, the tikz picture is outside of the paper. When I replace 10 by a bigger number, the pictures goes even further to the right. Any idea ?

\documentclass{article}

\usepackage{tikz}
\usepackage{pgfplots}

\pgfmathdeclarefunction{myfunction}{1}{
\let\x\pgfmathresult
\pgfmathsetmacro\ret{0}
\foreach \i in {1,...,10}{
\pgfmathsetmacro\ret{\ret + \x^\i}
\xdef\ret{\ret}
}
\pgfmathparse{\ret}
}

\begin{document}

\begin{tikzpicture}
\begin{axis}[axis lines=middle, domain=-1:1]
\end{axis}
\end{tikzpicture}

\end{document}


As mentioned in the comment, add percent signs. (one of the percent sign can be omitted in this case with no harm because of TeX rules, but in this particular case it's okay to have all of them as well.)

\documentclass{article}

\usepackage{tikz}
\usepackage{pgfplots}

\pgfmathdeclarefunction{myfunction}{1}{%
\let\x\pgfmathresult
\pgfmathsetmacro\ret{0}%
\foreach \i in {1,...,10}{%
\pgfmathsetmacro\ret{\ret + \x^\i}%
\xdef\ret{\ret}%
}%
\pgfmathparse{\ret}%
}

\begin{document}

\begin{tikzpicture}
\begin{axis}[axis lines=middle, domain=-1:1]
\end{axis}
\end{tikzpicture}

\end{document}


Alternatively use expl3 syntax, but this ignores all spaces and does some other changes, so make sure you know what you do.

\ExplSyntaxOn
\pgfmathdeclarefunction{myfunction}{1}{
\let\x\pgfmathresult
\pgfmathsetmacro\ret{0}
\foreach \i in {1,...,10}{
\pgfmathsetmacro\ret{\ret + \x^\i}
\xdef\ret{\ret}
}
\pgfmathparse{\ret}
}
\ExplSyntaxOff