7

I'm trying to use pgfmath to calculate a modular value. However, when I try to give this value as a label to a node, it does not compile.

The following code fails:

\documentclass{article}

\usepackage{tikz}

\begin{document}

\begin{tikzpicture}

    \pgfmathsetmacro{\N}{5}

    \foreach \x in {0,...,\N}
    {
        \pgfmathtruncatemacro{\next}{Mod(\x+1,\N)}
        \node at (\next,0) {\next};
%        \node at (\next,0) {\x};
    }

\end{tikzpicture}

\end{document}

It gives the error: "Missing } inserted. } l.16 }". Line 16 is the line with the "}".

The code where I replace the line with "\node" with the line that was commented out, it does compile (as an example). Could someone please explain what is going wrong, and how I can fix it?

I tried to do what is done in this answer, but math mode doesn't seem to help me.

Thanks!

2 Answers2

5

Don't use \next, since it's special. It's used throughout the kernel and could be redefined, leading to the issue you're experiencing. Instead, use something more descriptive like \nextnode.

Werner
  • 603,163
  • It is in pgfrcs.code.tex line 67-73. The weird thing is that PGF usually protects its next, such as \@next in tikz.code.tex. – Symbol 1 May 01 '17 at 20:25
  • @Symbol1 That's the TeX primitive \next for plain TeX compatibility looking for package input before loading anything yet. – percusse May 01 '17 at 21:07
  • @percusse really? I think I need a reference. – Symbol 1 May 01 '17 at 21:33
  • @Symbol1: When you use \nextnode and add \tracingmacros1 (even inside a group) around the \node part and then view your .log, you'll see some reference to \next that still exists. – Werner May 01 '17 at 21:39
  • @Werner I saw two \next that come from tikz.code.tex. So my previous comment is totally wrong. – Symbol 1 May 01 '17 at 21:43
  • OK I get it. The \next is probably used to absorb the { in the construction \node{text};. – Symbol 1 May 01 '17 at 21:49
1

When TikZ process your node, it uses

\let\next=

to absorb the begin-group character { in your code

\node at (\next,0) {\next};

Therefore \next will be Mod(\x+1,\N) until TikZ enters the node.

That is the reason why you can use \next in the coordinate

\node at (\next,0) {\x};

but cannot use it in a node.

Symbol 1
  • 36,855