我只是想向现有命令/变量添加一些元素,但没有成功。有很多关于如何实现该目标的不同方法的示例,但似乎没有一个对我有用。
在以下最小工作示例中,我尝试从那里复制解决方案https://tex.stackexchange.com/a/101694/109350
\documentclass{article}
\usepackage[utf8]{inputenc}
\title{MWS}
\author{r2p2}
\date{July 2016}
\newcommand{\features}[0]{}
\newcommand{\feature}[1] {
\let\oldfeatures\features
\renewcommand{\features}[0]{\oldfeatures, #1}
}
\feature{one}
\feature{two}
\feature{three}
\begin{document}
\maketitle
\section{Introduction}
\features
\end{document}
但我明白
TeX capacity exceeded, sorry [input stack size=5000].
\oldfeatures ->\oldfeatures
, two
作为错误消息,这不应该发生,因为 oldfeatures 只是 features 的旧副本,本身不包含 features。我错过了什么?
提前致谢。
答案1
\newcommand*\features{}
\newcommand*\feature[1]
{\ifx\features\empty
\def\features{#1}%
\else
\expandafter\def\expandafter\features\expandafter{\features, #1}%
\fi}
无论如何,LaTeX2e 都提供了\g@addto@macro
处理一般情况的功能。
\makeatletter
\newcommand*\features{}
\newcommand*\feature[1]
{\ifx\features\empty
\def\features{#1}%
\else
\g@addto@macro\features{, #1}%
\fi}
\makeatother
答案2
您不能根据宏本身来定义宏。有几种方法可以完成您想要的操作,简单或复杂。
以下是最简单的
\makeatletter
\let\features\@gobble
\makeatother
\newcommand{\feature}[1]{%
\expandafter\def\expandafter\features\expandafter{\features,#1}%
}
后
\feature{one}
\feature{two}
\feature{three}
扩大\features
将是
> \features=macro:
->one,two,three.
(您会看到开头没有逗号)。
\features
但是,如果你在还没有添加任何内容时尝试使用,则会出现问题。etoolbox
你可以做得更好:
\usepackage{etoolbox}
\newcommand{\features}{}
\newcommand{\feature}[1]{%
\ifdefempty{\features}
{\appto\features{#1}}
{\appto\features{,#1}}%
}