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".

1
  • @adam Thanks! I'm constantly visiting this wonderful site, for any doubt (at least) one answer can be found! Commented Mar 6, 2014 at 17:51

2 Answers 2

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.

6
  • Thank you very much! I'm really a newbie with latex, have supposed the expansion problem but no idea about how to solve it! Thanks a lot! Commented Mar 6, 2014 at 17:19
  • The \begingroup\edef\x{\endgroup trick is not necessary here; just \expandafter\edef\csname#1\endcsname{\thecount} is sufficient.
    – egreg
    Commented Mar 6, 2014 at 17:34
  • one can do \expandafter\def\csname#1\expandafter\endcsname\expandafter{\the\csname c@count\endcsname} but it is arguably quite some trouble to avoid an \edef.
    – user4686
    Commented Mar 6, 2014 at 17:42
  • In fact, it works! why? Commented Mar 6, 2014 at 17:43
  • @manuel \edef makes the required expansion. Commented Mar 6, 2014 at 17:45
5

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

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

You must log in to answer this question.

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