6

I defined a command in the preamble that allows something to be repeated n times

\def\myrepeat#1#2{\count0=#1 \loop \ifnum\count0>0 \advance\count0 by -1 #2\repeat}

so \myrepeat{3}{foo} is the same as typing foofoofoo.

Every time I use the \myrepeat command in the body, the page numbering is reset to 0. Why is that happening, and is there an easy way to fix this?

Here is an example that illustrates the problem:

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

Thank you.

  • 1
    Use another count, count4 for example. – Sigur Dec 23 '13 at 16:58
  • 1
    Using a different count solved the problem. Thanks! – Floyd Dec 23 '13 at 17:03
  • @Sigur Out of curiosity, was the issue that \count by default calls the "first" counter, which is the page counter? – Dennis Dec 23 '13 at 17:06
  • 2
    \thepage is \csname @arabic\endcsname \c@page and \c@page is \count0. – Sigur Dec 23 '13 at 17:13
  • For temporary storage, use \count255 rather than \count0; note that the values of \count0 to \count9 are stored in the DVI or PDF file during shipout of a page. – egreg Dec 23 '13 at 18:04
7

The counter \count0 stores the current page number, so it's not a good idea to use it for temporary storage; it could be by enclosing the code in a group, but it's not recommended if something is to be printed, because printing a paragraph may trigger the page builder at unexpected times and so give the page the wrong number.

LaTeX provides two counters for temporary storage, \@tempcnta and \@tempcntb; one can also use \count@, which is the same as \count255.

There are better ways to print repeated copies of a token list. The simplest one is with LaTeX3 features:

\documentclass{article}

\usepackage{xparse}

\ExplSyntaxOn
\NewDocumentCommand{\irepeat}{ m m }
{
 \prg_replicate:nn { #1 } { #2 }
}
\ExplSyntaxOff

\begin{document}

\irepeat{3}{foo}

\end{document}

enter image description here

With \numexpr and standard LaTeX techniques it could be

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

With a loop

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.