4

In the following code I intend to implement a loop that calls a macro that increases a count register \a on each pass, then displays the values of both \a and the loop control variable.

\newcount\a\newcount\counter
\def\test{\advance\a by 2 \the\a \quad\the\counter\par}
\loop\advance\counter by 1\ifnum\counter<20 {\test}\repeat
\bye

The result (below) shows that the macro always treats \a as if it wasn't previously defined. How can I get a global counter to be updated within a macro (for the output to read (2 1, 4 2, 6 3,...)) ?

2 1
2 2
2 3
2 4
2 5 
...
1
  • 1
    \global\advance\a
    – user31729
    Commented Aug 3, 2016 at 22:03

2 Answers 2

7

You need \global since plain TeX counters are group safe. Your \test macro runs within a group here (unnecessarily!) (Just remove the {...})

\newcount\a\newcount\counter
\def\test{\global\advance\a by 2 \the\a \quad\the\counter\par}
\loop\advance\counter by 1\ifnum\counter<20 {\test}\repeat
\bye

enter image description here

3

The answer was to call \test w/o it being enclosed in braces.

You must log in to answer this question.