1

So I have a couple variables defined in a TikZ image (specifically an x-value and a y-value of a point), and I'd like to be able to redefine them by adding some value to each. But I'm running into two problems:

  1. LaTeX doesn't want to do mathematical operations on variables. So \def \a{1+1} literally sets \a to "1+1" instead of 2.

  2. Redefining a variable in terms of itself throws LaTeX into (what I think is) a recursion error. \def \a{\a + 1} leads to the error "TeX capacity exceeded, sorry [input stack size=5000]."

I'd ideally like to do this:

\def \a{0}

% lots of code here

\def \a{\a + 2}

% after this line, I want \a to equal 2, not "0 + 2"

Is there a way to get this result with pgf or something?

2
  • 1
    why not go for pgfmathsetmacro
    – js bibra
    Apr 11, 2021 at 2:41
  • 2
    You cannot \def a macro in terms of itself. You have two options: \edef, if possible. Or else, \let\sva\a and the \def\a in terms of \sva. Apr 11, 2021 at 3:00

1 Answer 1

3

You can perform elementary numeric expressions using \numexpr<expr>:

\documentclass{article}

\begin{document}

\def\aaa{0}
\aaa
% lots of code here

\edef\aaa{\number\numexpr\aaa + 2}
\aaa

% after this line, I want \a to equal 2, not "0 + 2"

\end{document}

The above outputs 0 and 2.

Better would be to use xfp; elementary integer calculations are possible via \inteval, otherwise you can use \fpeval:

\documentclass{article}

\usepackage{xfp}

\begin{document}

\def\aaa{0}
\aaa
% lots of code here

\edef\aaa{\inteval{\aaa + 2}}
\aaa

% after this line, I want \a to equal 2, not "0 + 2"

\end{document}
1
  • Thank you! I tried xfp and it works like a charm.
    – theta0
    Apr 12, 2021 at 3:02

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .