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.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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 :


\foreach \size / \colorRectangle in {100pt/NavyBlue, 90pt/DarkRed, 60pt/DarkGreen, 40pt/DarkMagenta} {
    \draw[fill=\colorRectangle] (\prev, 5pt) rectangle +(\size, -10pt);

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
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
@egreg Added to my TODO list. – cjorssen Oct 31 '11 at 14:10

Your Answer


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.