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.

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 ?

share|improve this question
add comment

1 Answer

up vote 6 down vote accepted

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.

share|improve this answer
    
No, \global\pgfmathaddtolength doesn't work. Somebody should do something about this: maybe something like \pgfmathXYZ* for making the assignment global, where XYZ is any of the suffixes. –  egreg Oct 30 '11 at 15:25
2  
@egreg Added to my TODO list. –  cjorssen Oct 31 '11 at 14:10
add comment

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.