5

I'm trying to create a list of rectangles of various sizes, starting at the end of the previous rectangle. I'm using a foreach loop with a TeX length, but I don't get the result I want, and I really don't understand why. Here is the code :

\documentclass[svgnames,smaller]{beamer}
\usepackage{tikz}
\usepackage[utf8]{inputenc}
\usetheme{Warsaw}

\begin{document}
\begin{frame}
\begin{tikzpicture}
\newlength{\prev}
\setlength{\prev}{30pt}
\foreach \size / \colorRectangle in {100pt/NavyBlue, 90pt/DarkRed, 60pt/DarkGreen, 40pt/DarkMagenta} {
    \draw[fill=\colorRectangle] (\prev, 5pt) rectangle +(\size, -10pt);
    \pgfmathaddtolength{\prev}{+\size};
}
\end{tikzpicture}
\end{frame}
\end{document}

As you can see if you run this piece of code, the length \prev is not what "it's supposed to be", and in the end I get a rectangle of size 100pt covered by one of size 90pt, then 60pt and 40pt (instead of a rectangle of 40pt, then one of 60pt, then one of 90pt, and one of 100pt -- a total of 290pt)

Any ideas ?

user8947
  • 277
  • 2
  • 9

1 Answers1

6

The \foreach loop places every iteration in a group, so all local changes do not survive to the next iteration. You need to advance \prev globally.

I don't think that \global\pgfmathaddtolength works, but \global\advance\prev\size would do it for simple lengths as shown in your example.

You could also use \global\prev=\prev at the end of the loop code instead to make \prev global.

Martin Scharrer
  • 262,582