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 ?


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.

|improve this answer|||||
  • 1
    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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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