表中的宏扩展顺序

表中的宏扩展顺序

我有一张大表(大约 300 个条目)。有时,我会有一系列具有相同值的条目(对于给定的列)。在这种情况下,我需要省略该值。我的所有值都存储在其他地方使用的变量中,因此,我无法简单地删除它们。为了克服这个问题,我创建了一个临时命令来维护我的值。用纯文本测试我的解决方案可以得到我想要的结果。但是,当我在表中应用我的解决方案时,结果是错误的。

MWE(我加了一个点以便更好地看到省略的值在哪里):

\documentclass{article}
\usepackage{ifthen}

\begin{document}

\newcommand{\myval}{}

\newcommand{\setMyVal}[1]{\renewcommand{\myval}{#1}}

\newcommand{\printOnlyFirstOccurence}[1]{
    \ifthenelse{\equal{\myval}{#1}}
        {.}
        {\setMyVal{#1}\myval}%else
}

Outside table:

\printOnlyFirstOccurence{a}

\printOnlyFirstOccurence{a}

\printOnlyFirstOccurence{b}

\printOnlyFirstOccurence{b}

\printOnlyFirstOccurence{b}



Behaviour inside table:

\begin{table}[h!]
\centering
\begin{tabular}{c|c} \hline
    \printOnlyFirstOccurence{a} & a \\ \hline
    \printOnlyFirstOccurence{a} & a \\ \hline
    \printOnlyFirstOccurence{b} & b \\ \hline
    \printOnlyFirstOccurence{b} & b \\ \hline
    \printOnlyFirstOccurence{b} & b \\ \hline
\end{tabular}

\end{table}

\end{document}

在上面的例子中,在表格之外我得到了:

a…b…

我在表格里得到了:

啊啊……

有人可以解释这种行为吗?

答案1

\myval对齐单元格形成组,因此一旦转到另一个单元格,的重新定义就会被忘记。在 的定义中使用\gdef\myval{.}而不是。使用 只会得到局部重新定义。\renewcommand{\myval}{#1}\setMyVal\renewcommand

\documentclass{article}
\usepackage{ifthen}

\begin{document}

\newcommand{\myval}{}

\newcommand{\setMyVal}[1]{\gdef\myval{#1}}

\newcommand{\printOnlyFirstOccurence}[1]{
    \ifthenelse{\equal{\myval}{#1}}
        {.}
        {\setMyVal{#1}\myval}%else
}

Outside table:

\printOnlyFirstOccurence{a}

\printOnlyFirstOccurence{a}

\printOnlyFirstOccurence{b}

\printOnlyFirstOccurence{b}

\printOnlyFirstOccurence{b}



Behaviour inside table:

\begin{table}[h!]
\centering
\begin{tabular}{c|c} \hline
    \printOnlyFirstOccurence{a} & a \\ \hline
    \printOnlyFirstOccurence{a} & a \\ \hline
    \printOnlyFirstOccurence{b} & b \\ \hline
    \printOnlyFirstOccurence{b} & b \\ \hline
    \printOnlyFirstOccurence{b} & b \\ \hline
\end{tabular}

\end{table}

\end{document}

在此处输入图片描述

相关内容