2

The following works:

\documentclass{article}
\usepackage{longtable}

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

enter image description here

The following does not work:

\documentclass{article}
\usepackage{longtable}

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

enter image description here

Why?

2 Answers2

5

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
   \advance\n by1
      \toks0=\expandafter{\the\toks0
         col1 & col2 & col3 \\\relax
      }%
   \repeat
   \the\toks0
\end{longtable}
\end{document}

Result

Heiko Oberdiek
  • 271,626
4

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%
\int_new:N\g_macmadness_int%

\newcommand{\runacross}[2]{%
  \int_gzero:N \g_macmadness_int 
  \prg_replicate:nn {#1}{%
    \int_gincr:N \g_macmadness_int 
    \int_compare:nNnTF {\g_macmadness_int } = {#1}{%
      #2\int_use:N \g_macmadness_int \tabularnewline
    }{%
      #2\int_use:N \g_macmadness_int &
    }
  }
}
\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}

enter image description here