我需要一個命令,使其第一次呼叫時的行為與下次呼叫時的行為不同。現在我使用\newcommand\foo{First\gdef\foo{Next}}
,即它第一次重新定義自己。
而且,我需要在某個時候「重置」它的含義,所以我定義了\newcommand\resetfoo{\gdef\foo{First\gdef\foo{Next}}}
。
但這在我看來相當困難。可能有一種常見的方法可以做到這一點,但我不知道(而且,我幾乎一無所知擴張)。解決此類問題的正確方法是什麼?
問題
正如問題所述,我需要一種更通用的方法:一些函數可以更改其定義n「擴展」(我不確定我是否在正確的地方使用了這個詞)。你會如何解決這個問題?我也需要必要的\resetfoo
。
如果還沒有以某種方式完成,我的想法是有一些命令\changedefinitionafter\foo{3}{OneTwoThree}{Next}
或類似的東西。expl3
也歡迎解決方案。
這是一個更通用的 MWE。
\documentclass{scrartcl}
\newcommand\foo{First\gdef\foo{Next}}
\newcommand\resetfoo{\gdef\foo{First\gdef\foo{Next}}}
\begin{document}
\foo~\foo~\foo
\resetfoo~\foo~\foo
\end{document}
另外,歡迎為問題標題提供標籤和建議。
答案1
看一下下面的例子:
\documentclass{article}
\newcounter{testcount}
\newcommand{\modifyme}{%
\addtocounter{testcount}{1}
\ifnum\thetestcount<3%
Hello
\fi
\ifnum\thetestcount>2%
World
\fi
}
\newcommand{\resetme}{\setcounter{testcount}{0}}
\begin{document}
\modifyme
\modifyme
\modifyme
\modifyme
\resetme
\modifyme
\end{document}
答案2
我喜歡使用計數器!這裡只\changedefinitionafter
修改了指定的數字後的擴充。
\documentclass{article}
\pagestyle{empty}% for cropping
\makeatletter
\newcount\count@foo
\newcount\nth@foo
\newcommand\changedefinitionafter[4]{
% #1: name of macro
% #2: exceptional occurence
% #3: normal expansion
% #4: exceptional expansion
\global\count@foo=0
\global\nth@foo=#2
\gdef#1{%
\advance\count@foo by 1
\ifnum\count@foo=\nth@foo
#4%
\else
#3%
\fi
}
\edef\resetname{reset\expandafter\@gobble\string#1}
\expandafter\gdef\csname \resetname \endcsname{\global\count@foo=0 }
}
\makeatother
\begin{document}
\obeylines
\changedefinitionafter\foo{3}{OneTwoThree}{Next}
\foo
\foo
\foo
\foo
\resetfoo
\foo
\foo
\foo
\foo
\end{document}
答案3
沒有計數器,但這種類型的每個命令有三個巨集:
\documentclass{article}
\makeatletter
\newcommand{\newchangingcommand}[4]{%
% #1 = macro name
% #2 = steps
% #3 = value until step #1
% #4 = value from step #1
\@namedef{\string#1@counter}{0}%
\@namedef{\string#1@limit}{#2}%
\def#1{%
% step the counter
\global\@nameedef{\string#1@counter}{\number\numexpr\@nameuse{\string#1@counter}+1\relax}%
\ifnum\@nameuse{\string#1@counter}=\@nameuse{\string#1@limit}\relax
\gdef#1{#4}#4%
\else
#3%
\fi
}%
}
\providecommand\@nameedef[1]{\expandafter\edef\csname#1\endcsname}
\makeatother
\newchangingcommand{\foo}{3}{Two}{Next}
\newchangingcommand{\foob}{2}{One}{Next}
\begin{document}
\foo--\foob\par
\foo--\foob\par
\foo--\foob\par
\foo--\foob\par
\end{document}
請注意,由於多種原因,在移動參數時使用此類命令會失敗。