5

I try to expand a string using a counter. I will use a very simple example:

\def\st{}
\setcounter{i}{1}
\expandafter\def\expandafter\st\expandafter{\st{ } \the\numexpr\value{i}}
\addtocounter{i}{1}
\texttt{\st}

One would expect the result to be '1'. Yet, the result is '2' because the counter increased after the expansion. So, I undestand that 'st' is always "interpreted" using the final value of 'i'. So, in an iteration of the counter 'i' one would get n n n n ... (where 'n' is the final value of 'i'). But I would like to get 1 2 ... n. How can this be done?

(I spent a lot of time trying to achieve this reault, alas, in vain!)

  • \edef rather than \def. But just use etoolbox macros. This would be done \def\st{} \setcounter{tmpi}{1} \eappto\st{\the\numexpr\value{tmpi}} \addtocounter{tmpi}{1} \texttt{\st}. – Manuel Dec 15 '17 at 9:18
  • Yes, it works. Thanks. It also works with \appto. (Weird, I had already tried \appto among other things ... Maybe in the wrong way, though). BTW, why didn't you post this solution as a regular answer? I would then could upvote you. – Alkis Dec 15 '17 at 11:04
4

You need full expansion. Also, you're adding unwanted braces and spaces.

\documentclass{article}

\def\st#1{}
\newcounter{i}
%\renewcommand{\thei}{\arabic{i}} % it's default

\begin{document}

\count255=0
\loop
\ifnum\count255<10
  \advance\count255 1
  \stepcounter{i}
  \edef\st{\st\space\thei}
\repeat

--\st--

\end{document}

enter image description here

At the first iteration, \st will gobble \space.

A different implementation with etoolbox

\documentclass{article}
\usepackage{etoolbox}

\def\st{}
\newcounter{i}
%\renewcommand{\thei}{\arabic{i}} % it's default

\begin{document}

\count255=0
\loop
\ifnum\count255<10
  \advance\count255 1
  \stepcounter{i}
  \eappto\st{\ifdefempty\st{}{ }\thei}
\repeat

--\st--

\end{document}
| improve this answer | |
  • Yes, this works too. Thanks. But it's a little more complicated than just using '\eappto' (instead of my '\expandafter') that Manuel suggested (See comments above). – Alkis Dec 15 '17 at 11:23
  • I review my comment (I can't edit it anymore). I just isolated \edef\st{\st\space\thei} from your code and put it in mine. It's even simpler than \eappto\st{}{\the\numexpr\value{i}} ! – Alkis Dec 15 '17 at 11:40

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.