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.

This is a very elementary question, I hope it is still OK to ask it here.

I'd like to do the following

    \documentclass{article}
    \usepackage{tikz}

    \begin{tikzpicture}

    \def \x {2}
    \def \y {\x + 2}

    \foreach \s in {\x,...,\y}
    {
    % Do things
    }

    \end{tikzpicture}

This gives me the error

    ! Illegal unit of measure (pt inserted).
    <to be read again>
                       +
    1.12 }

Why is this not possible?

share|improve this question

4 Answers 4

up vote 8 down vote accepted

TeX doesn't parse math as you want it to do. Here, \foreach might be flexible enough to understand it but in general it is a bad idea.

You can force it via PGF math such as

\pgfmathsetmacro\x{2}
\pgfmathsetmacro\y{int(\x + 2)} %without int \y would be 4.0 instead of 4

\foreach \s in {\x,...,\y}
{
% Do things
}
share|improve this answer

A recommended solution with fp.

\documentclass[tikz,border=12pt,12pt]{standalone}
\usepackage[nomessages]{fp}
\FPset\x{2}
\FPeval\y{x+2}

\begin{document}
\begin{tikzpicture}

\foreach \s in {\x,...,\y}
{
    % Do things
    \draw (\s,\s) node {\s};
}

\end{tikzpicture}
\end{document}

enter image description here

share|improve this answer

The tikz way of assigning a value to a macro (\y, here) using that of another macro (\x, here) is to use

  • \pgfmathsetmacro (\y's value is then a fixed-point number), or
  • \pgfmathtruncatemacro (for an integer value).

Here is an example.

enter image description here

\documentclass{article}
\usepackage{tikz}

\begin{document}

\def\x{2}
\pgfmathsetmacro\xii{\x+0.25*\x}
\pgfmathsetmacro\y{\x+4.5}      

\foreach \s in {\x,\xii,...,\y}{\s,\ }

\end{document}
share|improve this answer

This is an expansion issue. When you use \def\y{...} \y takes the value that {....} has at the time of use, not at the time the definition was made.

Assuming that you're working with integer values, what you want is probably something like

\edef\y{\number\numexpr\x+2\relax}
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.