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?

  • 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
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

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

  • 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

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.