我正在尝试使用宏来构建一个我经常使用的表格,但表格末尾总是多出一行。宏实现基于以下答案: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
您无法这样做,\@ifnextchar
因为一旦 TeX 执行它,就会开始一个新的表格单元格。
你可以这样做\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}
另一种实现方式是,可以添加代码以确保参数数量为偶数。这里数据首先存储在令牌寄存器中,以便立即传送。
\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}