[Tex/LaTex] Tikzmath, ERROR: Missing \endcsname inserted

tikz-pgftikzmath

I'm trying to use tikzmath to draw lines between a set of points, however I've an error ERROR: Missing \endcsname inserted. on the line \ni=\i+1;. Any idea why?

\documentclass{article}

\usepackage{tikz}
\usetikzlibrary{math,calc}

\begin{document}

\begin{tikzpicture}
  \tikzmath{
    \n=5;
  }
  \foreach \i in {-\n,...,\n} {
    \foreach \j in {-\n,...,\n} {
      \node[circle,fill,inner sep=1pt] at ($(\i+.3*\j,.5*\j)$) (n-\i-\j) {};
    }
  }
  \foreach \i in {-\n,...,\n-1} {
    \foreach \j in {-\n,...,\n-1} {
      \tikzmath{%
        \ni=\i+1;
        \nj=\j+1;
      };
      \draw[] (n-\i-\j) -- (n-\i-\nj);
    }
  }
\end{tikzpicture}
\end{document}

Best Answer

Due to how \tikzmath works, you can’t use variable names that correspond to already defined commands that point to mathematical symbols.

The standard definition of \ni is by \mathchardef\ni="3233 (in a glorified form in fontmath.ltx) and TeX considers \mathchardef tokens as numbers when it’s looking for them.

The same error happens, for instance, if I use \propto instead of \ni.

Use another name.

With other fixes, as suggested by percusse:

\documentclass{article}

\usepackage{tikz}
\usetikzlibrary{math,calc}

\begin{document}
\pagestyle{empty}

\begin{tikzpicture}
  \tikzmath{
    \n=5;
  }
  \foreach \i in {-\n,...,\n} {
    \foreach \j in {-\n,...,\n} {
      \node[circle,fill,inner sep=1pt] at ($(\i+.3*\j,.5*\j)$) (\n-\i-\j) {};
    }
  }
  \foreach \i in {-\n,...,\numexpr\n-1} {
    \foreach \j in {-\n,...,\numexpr\n-1} {
      \tikzmath{%
        \nni=\i+1;
        \nj=\j+1;
      };
      \draw[] (\n-\i-\j) -- (\n-\i-\nj);
    }
  }
\end{tikzpicture}
\end{document}