
ネストされたループなど、異なるブロック間でカウント値を保持するにはどうすればよいでしょうか? たとえば
\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
。この問題の核心は、{...}
中括弧には 2 つの意味があることです。中括弧はグループを開始および終了し、分離されたパラメータの内部セパレータを保護します。中括弧は (2 番目の意味のため) 使用したいのですが、グループを開始/終了せずに使用します。
\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
)、2 つ\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}