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

  • @adam Thanks! I'm constantly visiting this wonderful site, for any doubt (at least) one answer can be found! – Manuel Ruiz Mar 6 '14 at 17:51
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.

  • 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! – Manuel Ruiz Mar 6 '14 at 17:19
  • The \begingroup\edef\x{\endgroup trick is not necessary here; just \expandafter\edef\csname#1\endcsname{\thecount} is sufficient. – egreg Mar 6 '14 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 Mar 6 '14 at 17:42
  • In fact, it works! why? – Manuel Ruiz Mar 6 '14 at 17:43
  • @manuel \edef makes the required expansion. – Gonzalo Medina Mar 6 '14 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}}}
  • 1
    @hebert This also works too! what is the different between \thecount and \arabic{count}? – Manuel Ruiz Mar 6 '14 at 17:54
  • write after the counter definition \renewcommand\thecount{\alph{count}} and see what happens with these two answers. – user2478 Mar 6 '14 at 18:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.