
如何使計數保留不同區塊之間的值,例如在巢狀循環中?例如
\newcommand\example
{%
\newcount\N
\loop
{\loop
\the\N\quad
\ifnum\N<5
\advance\N by 1
\repeat
}%
\the\N
\ifnum\N<5
\advance\N by 1
\repeat
}
將返回
0 1 2 3 4 5
0
1 2 3 4 5
1
2 3 4 5
2
3 4 5
3
4 5
4
5
5
如何才能保留 的值\N
並因此實現這樣的輸出?
0 1 2 3 4 5
5
答案1
您必須全域設定計數器。
請注意,\newcount\N
絕對不屬於 的替換文字\example
。
\documentclass{article}
\newcount\N
\newcommand\example{%
\global\N=0
\loop
{\loop
\the\N\quad
\ifnum\N<5
\global\advance\N by 1
\repeat
}%
\par
\the\N\par
\ifnum\N<5
\global\advance\N by 1
\repeat
}
\begin{document}
\example
\end{document}
或者,您可以使用以下方式\expandafter
聯絡群組外:
\newcount\N
\newcommand\example{%
\N=0
\loop
{\loop
\the\N\quad
\ifnum\N<5
\advance\N by 1
\repeat
\expandafter
}\expandafter\N\the\N\relax
\par
\the\N\par
\ifnum\N<5
\advance\N by 1
\repeat
}
答案2
如果您不需要在內循環中全域設定該值,那麼您可以定義\nogroup
.這個問題的核心是:{...}
大括號有兩個意義:它們打開和關閉群組,並且它們保護分隔參數的內部分隔符號。我們想使用它們(因為第二個含義)但沒有打開/關閉群組:
\newcount\N
\def\nogroup#1{#1}
\def\example
{%
\loop
\nogroup{\loop
\the\N\quad
\ifnum\N<5
\advance\N by 1
\repeat
}%
\endgraf
\the\N
\endgraf
\ifnum\N<5
\advance\N by 1
\repeat
}
\example
\bye
答案3
您可以使用不進行賦值的循環,因此不需要將內部循環包裝在大括號對中以避免覆蓋。
我完全接管了您的示例(嗯..不,我們不想\newcount\N
每次使用都執行多次\example
!)並且僅將兩個替換\loop
為\xintloop
.它的設計目的是刪除用於隱藏內部的大括號,\repeat
因此在退出外部循環時保留計數步進。
\documentclass{article}
\usepackage{xinttools}
\begin{document}
\newcount\N
\newcommand\example
{%
\xintloop
{\xintloop
\the\N\quad
\ifnum\N<5
\advance\N by 1
\repeat
}%
\the\N
\ifnum\N<5
\advance\N by 1
\repeat
}
\example
\end{document}