# Why does a loop fail to repeat when filling longtable contents?

The following works:

\documentclass{article}
\usepackage{longtable}

\begin{document}
\newcount\n
\n=0
\begin{longtable}{ccc}
\loop
\ifnum\n<10
hello
\repeat
\end{longtable}
\end{document}


The following does not work:

\documentclass{article}
\usepackage{longtable}

\begin{document}
\newcount\n
\n=0
\begin{longtable}{ccc}
\loop
\ifnum\n<10
col1 & col2 & col3 \\
\repeat
\end{longtable}
\end{document}


Why?

• Your 2nd loop example tries to run across table cells -- this can't work this way. – user31729 Apr 3 '16 at 20:51
• you find here an idea – touhami Apr 3 '16 at 20:52

The cells in table environments (tabular, longtable, ...) are also groups, thus the internal loop definitions and the value for \n are lost after the first cell/group.

Typical workaround is to put the contents into a macro or token register first:

\documentclass{article}
\usepackage{longtable}

\begin{document}
\newcount\n
\n=0
\begin{longtable}{ccc}
\n=0
\toks0={}%
\loop
\ifnum\n<10
\toks0=\expandafter{\the\toks0
col1 & col2 & col3 \\\relax
}%
\repeat
\the\toks0
\end{longtable}
\end{document}


Here's a \prg_replicate:nn version that works over cell boundaries and get's finished after that.

\documentclass{article}
\usepackage{longtable}

\usepackage{xparse}

\ExplSyntaxOn%

\newcommand{\runacross}[2]{%
\prg_replicate:nn {#1}{%
}{%
}
}
}
\ExplSyntaxOff

\newcounter{cols}
\setcounter{cols}{10}
\begin{document}

\begin{longtable}{*{\number\value{cols}}{c}}
\runacross{\number\value{cols}}{col}
\runacross{\number\value{cols}}{Foo}
\end{longtable}
\end{document}


• Now I would have lost a bet. I thought, this solution was given bei clemens...nice solution. – Peter Ebelsberger Apr 3 '16 at 21:33
• @PeterEbelsberger: Thanks. I've learned (a bit) of expl3 already – user31729 Apr 4 '16 at 9:11