我尝试定义一个宏\onoff
,每次使用时交替打印“on”和“off”。例如,该序列\onoff \onoff \onoff
将打印on off on
我的第一个猜测是使用以下代码:
\def\a{on}
\def\b{off}
\newcommand\onoff{\a\def\c{\a}\def\a{\b}\def\b{\c}}
但是这段代码不起作用。有没有一种优雅的方法来编写这段代码?
答案1
单程
\documentclass{article}
\makeatletter
\def\@ONoff {on\let\onoff\@onOFF}
\def\@onOFF {off\let\onoff\@ONoff}
\let\onoff\@ONoff
\makeatother
\begin{document}
\onoff\onoff\onoff\onoff\onoff\onoff...
\end{document}
另一种方法(现已删除单独的答案)
\documentclass{article}
\makeatletter
\def\onoff{\@onoff{on}{off}}
\def\@onoff #1#2{#1\def\onoff {\@onoff{#2}{#1}}}
\makeatother
\begin{document}\thispagestyle{empty}
\onoff\onoff\onoff\onoff\onoff\onoff...
\end{document}
第三种方法
\documentclass{article}
\makeatletter
\def\onoff {\onoroff{on\let\onoroff\@secondoftwo}{off\let\onoroff\@firstoftwo}}
\let\onoroff\@firstoftwo
\makeatother
\begin{document}
\onoff\onoff\onoff\onoff\onoff\onoff\onoff...
\onoff\onoff\onoff\onoff\onoff...
\end{document}
答案2
使用etoolbox
布尔值和我制作的最棒的 TikZ-foo。
\documentclass{article}
\usepackage{etoolbox}
\usepackage{parskip}
\usepackage{tikz}
\newbool{volt}
\newcommand{\onoff}{%
\ifbool{volt}{%
\boolfalse{volt}\candleOn\space ON}{%
\booltrue{volt}\candleOff\space OFF}%
}
\newcommand{\candleOff}{\tikz \draw (0,0) rectangle
(.2,.8);}
\newcommand{\candleOn}{\begin{tikzpicture}\draw (0,0) rectangle
(.2,.8);\draw [fill=orange] (.1,.9) circle
[radius=.1];\end{tikzpicture}}
\begin{document}
\onoff\par
\onoff\par
\onoff\par
\onoff\par
\end{document}
答案3
使用条件
\documentclass{article}
\newif\ifoff
\newcommand{\onoff}{%
\relax\ifoff off\global\offfalse\else on\global\offtrue\fi
}
\begin{document}
\onoff
\onoff
\onoff
\end{document}
或计数器
\documentclass{article}
\newcount\offcount
\newcommand{\onoff}{%
\relax
\ifodd\offcount
\global\advance\offcount 1
off%
\else
\global\advance\offcount -1
on%
\fi
}
\begin{document}
\onoff
\onoff
\onoff
\end{document}
在这两种情况下,如果您只想要本地重新定义,请删除\global
。
\relax
请注意,如果您想\onoff
在表格中使用,则必须以 为起始点。
抽象版本,借助etoolbox
它可以通过切换使事情变得更容易一些(可以通过条件实现)。
\documentclass{article}
\usepackage{etoolbox}
\newcommand{\newalternatingcommand}[3]{%
\newcommand{#1}{%
\iftoggle{\string#1}
{#2\global\togglefalse{\string#1}}
{#3\global\toggletrue{\string#1}}%
}%
\newtoggle{\string#1}%
\toggletrue{\string#1}%
}
\newalternatingcommand{\onoff}{on}{off}
\begin{document}
\onoff
\onoff
\onoff
\end{document}
答案4
例如:
\def\onoffA{on\gdef\onoff{off\global\let\onoff=\onoffA}} \let\onoff=\onoffA
Test: \onoff, \onoff, \onoff, \onoff, \onoff, \onoff.
\bye