Take the 2-minute tour ×
TeX - LaTeX Stack Exchange is a question and answer site for users of TeX, LaTeX, ConTeXt, and related typesetting systems. It's 100% free, no registration required.

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

share|improve this question

1 Answer 1

up vote 8 down vote accepted

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}
share|improve this answer
    
exact ! Possible \global\let\posx\pgfmathresult –  Alain Matthes Jan 2 '12 at 20:48

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.