
我在序言中定義了一個命令,允許某些內容重複 n 次
\def\myrepeat#1#2{\count0=#1 \loop \ifnum\count0>0 \advance\count0 by -1 #2\repeat}
所以 \myrepeat{3}{foo} 與輸入 foofoofoo 相同。
每次我在正文中使用 \myrepeat 指令時,頁碼都會重設為 0。
下面是一個說明問題的範例:
\documentclass[]{article}
\def\irepeat#1#2{\count0=#1 \loop \ifnum\count0>0 \advance\count0 by -1 #2\repeat}
\begin{document}
The page number here is 1.
\newpage
\irepeat{3}{foo}
The page number here is 0.
\newpage
And 1 again.
\end{document}
謝謝。
答案1
計數器\count0
存儲當前頁碼,因此用它來臨時存儲並不是一個好主意;可以透過將程式碼封裝在一個群組中,但如果要列印某些內容,則不建議這樣做,因為列印段落可能會在意外的時間觸發頁面建立器,從而給頁面提供錯誤的編號。
LaTeX 提供了兩個用於暫存的計數器,\@tempcnta
並且\@tempcntb
;也可以使用\count@
,與 相同\count255
。
有更好的方法來列印令牌清單的重複副本。最簡單的一種是 LaTeX3 功能:
\documentclass{article}
\usepackage{xparse}
\ExplSyntaxOn
\NewDocumentCommand{\irepeat}{ m m }
{
\prg_replicate:nn { #1 } { #2 }
}
\ExplSyntaxOff
\begin{document}
\irepeat{3}{foo}
\end{document}
使用\numexpr
標準的 LaTeX 技術,它可以是
\documentclass{article}
\makeatletter
\newcommand{\irepeat}[2]{%
\ifnum#1>\z@
#2%
\expandafter\@firstofone
\else
\expandafter\@gobble
\fi
{\expandafter\irepeat\expandafter{\number\numexpr#1-1\relax}{#2}}%
}
\makeatother
\begin{document}
\irepeat{3}{foo}
\end{document}
帶循環
\documentclass{article}
\makeatletter
\newcommand\irepeat[2]{%
\@tempcnta=#1\relax % or \@tempcntb or \count@
\loop\ifnum\@tempcnta>\z@
\advance\@tempcnta by \m@ne
#2%
\repeat
}
\makeatother
\begin{document}
\irepeat{3}{foo}
\end{document}