블록 간 개수 값 유지

블록 간 개수 값 유지

예를 들어 중첩 루프에서 서로 다른 블록 사이의 값을 유지하는 카운트를 만드는 방법은 무엇입니까? 예를 들어

\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}

여기에 이미지 설명을 입력하세요

관련 정보