# Save counter value inside command?

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

-
Welcome to TeX.SX! –  Adam Liter Mar 6 '14 at 17:24
@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

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}


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. –  jfbu 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

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

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

-
@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. –  Herbert Mar 6 '14 at 18:45