14

I'm trying to automatically generate commands based on the value of a counter:

\documentclass{article}

\newcounter{count}

\newcommand\generator[1]%
{%
  \stepcounter{count}%
  \expandafter\def\csname#1\endcsname{\thecount}%
}

\generator{one}
\generator{two}

\begin{document}
  \one
  \two
\end{document}

the expected output would be "12" instead of "22".

2 Answers2

6

It's an expansion problem; \thecount needs to be expanded first:

\documentclass{article}

\newcounter{count}

\newcommand\generator[1]%
{%
  \stepcounter{count}%
  \expandafter\edef\csname#1\endcsname{\thecount}%
}

\generator{one}
\generator{two}

\begin{document}
  \one
  \two
\end{document}

enter image description here

This was similar to a problem I had and motivated A problem with counters; I inititially used basically egreg's approach from his answer there, but egreg himself has pointed out in a comment that in this case it's enough to use \edef; I've updated my answer accordingly.

Gonzalo Medina
  • 505,128
5

if you need only the value and not its representation use :

\newcommand\generator[1]{%
  \stepcounter{count}%
  \expandafter\edef\csname#1\endcsname{\arabic{count}}}
  • 1
    @hebert This also works too! what is the different between \thecount and \arabic{count}? – Manuel Ruiz Mar 06 '14 at 17:54
  • write after the counter definition \renewcommand\thecount{\alph{count}} and see what happens with these two answers. –  Mar 06 '14 at 18:45