# How to expand a string macro using a counter?

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}}
\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

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
\stepcounter{i}
\edef\st{\st\space\thei}
\repeat

--\st--

\end{document}


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