TransWikia.com

Is there something like renewcounter or providecounter?

TeX - LaTeX Asked by Didii on July 25, 2021

Is there a command that creates a counter or, if it already exists, redefines it? Thing is that I’m working with nested loops. The second loop is however in a command. This means if I want to use a second counter for the second loop, I need to define it before the first loop and give it as an argument in the command which seems a bit cumbersome.

As example:

newcommandrecursiveloop[2]{% do loop with counter #2, #1 times
  setcounter{#2}{0}
  {loopunlessifnumvalue{#2}=#1
    stepcounter{#2}
    % do something
  repeat}
}

newcounter{loop}     % counter for first loop
newcounter{recloop}  % counter for recursive loop

loopunlessifnumtheloop=4  % start the first loop
  stepcounter{loop}  % counter loop +1
  % do something
  recursiveloop{3}{recloop}  % call command to run second loop
repeat

In this example it’s of course not a big deal. But my command has already 3 arguments and more will be added.. Isn’t there a way of (1) check if the counter exists to run the appropriate command: setcounter or newcounter or (2) a command that can do it by himself.

2 Answers

No, renewcounter and providecounter don't exist and they shouldn't.

By way of example, suppose you say

providecounter{page}

loopunlessifnumvalue{loop}=4  % start the first loop
  stepcounter{loop}  % counter loop +1
  % do something
  recursiveloop{3}{page}  % call command to run second loop
repeat

and recursiveloop does stepcounter{page}: chaos will ensue even if the loop is in a group, because stepcounter, addtocounter and setcounter always act globally.

Of course you'd not use page, but what would happen if you choose a name already referring to some counter that's defined in a package you load and stores some important value?

Always allocate your own counters in the preamble or use the scratch counters provided by LaTeX (@tempcnta and @tempcntb).

By the way, don't use theloop for numeric tests, but value{loop}, which stores the value in a form which is independent from the value's representation.

Correct answer by egreg on July 25, 2021

If you really need renewcounter then writing it is really simple: defrenewcounter#1{expandafterifcsname c@#1endcsnameelsenewcounter{#1}fi setcounter{#1}{0}. However, its use cases are indeed quite rare. The previous answer claims that it should “never” be used, which is, as quite often for such claims, an exaggeration; an example of a specific use case is an exam file, which includes some exercise files, each of which may define (through renewcounter) their own, independent question counters.

Answered by Circonflexe on July 25, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP