4
\documentclass{standalone}
\usepackage{tikz}

\newcounter{xi}
\setcounter{xi}{0}

\newcommand{\foo}[0]{
    \addtocounter{xi}{1};
    \coordinate (x{\value{xi}}) at (1,2);
}

\begin{document}
\begin{tikzpicture}
    \foo{};
\end{tikzpicture}
\end{document}

Every time I call \foo I want a new node to be initialized, a new node with name "xK", where K is the value of the counter being increased automatically at each call.

Peter Grill
  • 223,288
Ilonpilaaja
  • 1,335

2 Answers2

5

Use \coordinate (x\the\value{xi}) at (1,2);. The following shows that the two nodes were indeed created by the multiple calls to \foo{}:

enter image description here

Reference:

Notes (thanks to @GonzaloMedina):

  • There is no need to set the counter to 0 - that is automatically done when creating a new counter.
  • The definition of \foo could also be given like this: \newcommand{\foo}{\stepcounter{xi}\coordinate (x\the\value{xi}) at (1,2);}.
  • No need to invoke \foo with an ending semicolon.

Having said that my personal preference is to initialize counters (programming habit), and to add a trailing ; within tikzpicture after each statement. I would not normally terminate the definition of \foo with a ; in which case the trailing ; would be required.

Code:

\documentclass{standalone}
\usepackage{tikz}

\newcounter{xi} \setcounter{xi}{0}

\newcommand{\foo}[0]{ \addtocounter{xi}{1}; \coordinate (x\the\value{xi}) at (1,2); }

\begin{document} \begin{tikzpicture} \foo{}; \foo{};

\node [circle, minimum size=3pt, inner sep=3pt, fill=blue                 ] at (x1) {};
\node [circle ,minimum size=6pt, inner sep=6pt, fill=red, fill opacity=0.5] at (x2) {};

\end{tikzpicture} \end{document}

Peter Grill
  • 223,288
1

And your question is?

When running your code, I get an error message, because \value{xi} does not yield text, but just the counter itself.

Replacing \value{xi} with \arabic{xi} makes the error go away, but I can't fathom whether the problem is solved now.