It seems that lengths are not updated in for loops. Compiling the code below:
\documentclass{article}
\usepackage{tikz}
\newlength{\test}
\newcommand{\inc}{\addtolength{\test}{1cm}}
\newcommand{\incs}{\foreach \x in {1,2,3} {\addtolength{\test}{1cm}}}
\begin{document}
Test: .\hspace{\test}.
\inc
Test: .\hspace{\test}.
\setlength{\test}{0cm}
\incs
Test: .\hspace{\test}.
\end{document}
We expect to see
Test: ..
Test: .--.
Test: .------.
But the last line shows
Test: ..
It is a bit annoying because I wanted to use a floating point number to be remembered in a TikZ picture, each time I call a function in a for loop.
EDIT I want to write code for a piecewise function. Here is what I have
\documentclass[12pt]{article}
\usepackage{tikz}
\newlength{\currX}
\setlength{\currX}{0mm}
\newlength{\currY}
\setlength{\currY}{0mm}
\newcommand{\drawbar}[2]{
\draw (\currX,\currY) -- (\currX,\currY+{#2}) -- (\currX+{#1},\currY+{#2});
\global\addtolength{\currX}{#1}
\global\addtolength{\currY}{#2}
}
\newcommand{\drawbars}[1]{
\foreach \x/\y in {#1}{
\drawbar{\x}{\y}
}
}
\begin{document}
\begin{figure}
\begin{tikzpicture}
\drawbar{2mm}{4mm}
\drawbar{20mm}{40mm}
\end{tikzpicture}
\end{figure}
\begin{figure}
\begin{tikzpicture}
\drawbars{2mm/4mm, 20mm/40mm}
\end{tikzpicture}
\end{figure}
\end{document}
I get a compile error:
You can't use a prefix with `\begingroup'.
<to be read again>
\begingroup
l.23 \drawbar{2mm}{4mm}
EDIT2
The second question turns out to be the same as TikZ, foreach and sum
Prefixing with global as suggested does not compile in my more specific example above, the solution above does well.

