4

I'm trying to use macros to build a table I'm using a lot, but I keep getting an extra line at the end of the table. The macro implementation is based on the answer at: https://tex.stackexchange.com/a/72915

\documentclass{article}
\begin{document}
\makeatletter
\newcommand{\start}{%
    \begin{center}
        \begin{tabular}{| l | c |}
            \hline
            \@iterate
}
\newcommand{\@iterate}{%
    \@ifnextchar\stop\@end\@step
}
\newcommand{\@step}[2]{%
    #1 & #2 \\ \hline
    \@iterate
}
\newcommand{\@end}[1]{%
            \end{tabular}
    \end{center}
}

\start
    {1}{2}
    {3}{4}
    \stop
 \end{document}

1
  • Welcome to TeX.SX! \@ifnextchar does not work by expansion and so, upon finding it TeX will start a new cell.
    – egreg
    Sep 20, 2017 at 8:38

1 Answer 1

6

You can't do it with \@ifnextchar because as soon as TeX executes it a new table cell will start.

You can do it with \ifx:

\documentclass{article}

\makeatletter
\newcommand{\starttb}{%
  \begin{tabular}{|l|c|}
  \hline
  \fc@iteration
}
\newcommand\fc@iteration[1]{%
  \ifx\stoptb#1%
    \expandafter\@firstoftwo
  \else
    \expandafter\@secondoftwo
  \fi
  {\end{tabular}}
  {\fc@absorb{#1}}%
}
\newcommand{\fc@absorb}[2]{%
  #1 & #2 \\ \hline
  \fc@iteration
}
\def\stoptb{}
\makeatother

\begin{document}

\starttb
  {1}{2}
  {3}{4}
\stoptb
\quad
\starttb
  {1}{2}
  {3}{4}
  {5}{6}
  {7}{8}
\stoptb

\end{document}

enter image description here

An alternative implementation, where code could be added for ensuring an even number of arguments. Here the data is first stored in a token register, to be delivered at once.

\documentclass{article}

\makeatletter
\newtoks\fc@table
\newcommand{\starttb}{%
  \fc@table={\begin{tabular}{|l|c|}\hline}%
  \fc@iteration
}
\newcommand\fc@iteration{%
  \@ifnextchar\stoptb{\fc@finish}{\fc@iterate}%
}
\newcommand{\fc@iterate}[2]{%
  \fc@table=\expandafter{\the\fc@table #1 & #2 \\ \hline}%
  \fc@iteration
}
\newcommand{\fc@finish}[1]{\the\fc@table\end{tabular}}
\def\stoptb{\stoptb}
\makeatother

\begin{document}

\starttb
  {1}{2}
  {3}{4}
\stoptb
\quad
\starttb
  {1}{2}
  {3}{4}
  {5}{6}
  {7}{8}
\stoptb

\end{document}

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .