[Tex/LaTex] foreach loop and calc

foreachtikz-pgf

Why doesn't \posx in the following loop change? I have added manually what should be the result (second picture on the left). Any way to fix this?

\documentclass{article}

\usepackage{tikz}
\usetikzlibrary{calc}
\usepackage{pgfplots}
\usepackage{tkz-fct}
\usetkzobj{all}

\usepackage{ifthen}

\begin{document}

\newcommand{\vt}[1]{
  \pgfmathsetmacro{\posx}{0}
  \foreach \x/\y in {#1}{
    \draw[color=red,thick] (\posx,\y) -- (\x + \posx,\y);
    \pgfmathsetmacro{\posx}{\x + \posx};
  }
  \node at (5,3) {posx: \posx};
}

\begin{tikzpicture}
   \tkzInit[xmax=6,ymax=4]
   \tkzGrid
   \tkzAxeXY
   \vt{1/1,2/2,3/3}
\end{tikzpicture}
\begin{tikzpicture}
   \tkzInit[xmax=6,ymax=4]
   \tkzGrid
   \tkzAxeXY
   \draw[color=red,thick] (0,1) -- (1,1);
   \draw[color=red,thick] (1,2) -- (3,2);
   \draw[color=red,thick] (3,3) -- (6,3);
\end{tikzpicture}


\end{document}

loop.jpg

Best Answer

Affectation are local inside a \foreach loop because the whole commands are inside a group. So you need to define things globally (see the use of \xdef).

\documentclass{article}

\usepackage{tikz}
\usetikzlibrary{calc}
\usepackage{tkz-fct}
\usetkzobj{all}

\begin{document}

\newcommand{\vt}[1]{
  \pgfmathsetmacro{\posx}{0}
  \foreach \x/\y in {#1}{
    \draw[color=red,thick] (\posx,\y) -- (\x + \posx,\y);
    \pgfmathparse{\x + \posx}
    \xdef\posx{\pgfmathresult}%
  }
  \node at (5,3) {posx: \posx};
}

\begin{tikzpicture}
   \tkzInit[xmax=6,ymax=4]
   \tkzGrid
   \tkzAxeXY
   \vt{1/1,2/2,3/3}
\end{tikzpicture}
\begin{tikzpicture}
   \tkzInit[xmax=6,ymax=4]
   \tkzGrid
   \tkzAxeXY
   \draw[color=red,thick] (0,1) -- (1,1);
   \draw[color=red,thick] (1,2) -- (3,2);
   \draw[color=red,thick] (3,3) -- (6,3);
\end{tikzpicture}

\end{document}