Take the 2-minute tour ×
TeX - LaTeX Stack Exchange is a question and answer site for users of TeX, LaTeX, ConTeXt, and related typesetting systems. It's 100% free, no registration required.

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

share|improve this question
    
Welcome to TeX.SX! –  Adam Liter Mar 6 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 at 17:51

2 Answers 2

up vote 6 down vote accepted

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.

share|improve this answer
    
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 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 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 at 17:42
    
In fact, it works! why? –  Manuel Ruiz Mar 6 at 17:43
    
@manuel \edef makes the required expansion. –  Gonzalo Medina Mar 6 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}}}
share|improve this answer
    
@hebert This also works too! what is the different between \thecount and \arabic{count}? –  Manuel Ruiz Mar 6 at 17:54
    
write after the counter definition \renewcommand\thecount{\alph{count}} and see what happens with these two answers. –  Herbert Mar 6 at 18:45

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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