8

I'm having trouble passing an argument to \pgfmathparse inside a macro I defined. Here is the code:

\documentclass{article}

\usepackage{tikz}

\usetikzlibrary{calc}

\newcommand{\drawmestg}[2]{
    \def\endpt{\pgfmathparse{#1+#2}\pgfmathresult}
    \draw (0,0) -- (\endpt,0);
}

\begin{document}
    \begin{tikzpicture}
        \drawmestg{1}{1}
    \end{tikzpicture}
\end{document}

I must confess, I'm quite clueless why I get the error:

Incomplete \iffalse; all text was ignored after line 14
Count Zero
  • 17,424
  • This is all to do with expansion. As well as Peter's answer, you might want to look for example at http://tex.stackexchange.com/questions/7811/how-to-use-pgf-math-inside-an-argument – Joseph Wright Nov 17 '11 at 21:40
  • I guess I really need to sit down and study a bit this expandability thing... It keep s popping up, but I don't really get it - yet! :) – Count Zero Nov 18 '11 at 14:44

2 Answers2

14

In the \draw command in your version \endpt is expanded to \pgfmathparse{#1+#2}\pgfmathresult. So you get

\draw (0,0) -- (\pgfmathparse{#1+#2}\pgfmathresult,0);

which greatly confuses TikZ.

Instead you should set \endpt to the result of the calculation, either via

\pgfmathsetmacro{\endpt}{#1+#2}

as Peter suggested or equivalently via

\pgfmathparse{#1+#2}
\edef\endpt{\pgfmathresult}

Alternatively for this MWE you can of course simply do

\newcommand{\drawmestg}[2]{
    \draw (0,0) -- ({#1+#2},0);
}
Caramdir
  • 89,023
  • 26
  • 255
  • 291
  • 6
    I like this answer because it took me one year of using TikZ before I figured out how to use arbitrary math in coordinates. The manual never says! – Ryan Reich Nov 17 '11 at 23:02
9

Simply use pgfmathsetmacro as in:

\pgfmathsetmacro{\endpt}{#1+#2}
Peter Grill
  • 223,288
  • 2
    @CountZero: Or \pgfmathparse{#1+#2}\let\endpt\pgfmathresult, which however is basically the same. The \enpt must be expandable, and \pgfmathparse isn't, so it can't be part of the macro. – Martin Scharrer Nov 17 '11 at 21:47