2

I am trying to delete a counter in my ".sty" file. Right now I have a few ".tex" files that use the same ".sty". They use the same ".sty" file to use \newcommands. However, when I go to make a new counter sometimes the counter may have the same name. When that is the case I get a compiler error since I'm trying to create something that is already defined. Is there a way I can delete the counter?

An example of what is happening in my code can be seen below:

\newcommand{\addMsg}[1] % This would be in the file.sty
{
    \newcounter{#1}
}

\addMsg{nameOfCounter}  % This would be in File1.tex
\addMsg{nameOfCounter}  % This would be in File1.tex

Keep in mind many people may edit these files, thus in file1.tex someone may put \addMsg{Counter1} and in file2.tex someone may also put \addMsg{Counter1}. Thus I cannot just simply make sure all counters are named differently.

1
  • Probably you should be clearer about how you want to use these counters. Surely, having the same counter used for different purposes is a recipe for disaster.
    – egreg
    Dec 23, 2019 at 21:36

1 Answer 1

5

You can't un-define a counter. You could overwrite its definition, but then you would waste counter memory (not a problem, nowadays, but. . .), or you'd need to mess with their lower level implementation. Much easier is to define a \providecounter macro which only defines a counter if it doesn't yet exist:

\documentclass{article}
\makeatletter
\def\providecounter#1{%
  \@ifundefined{c@#1}%
    {\newcounter{#1}}{\@newctr}}
\makeatother

\providecounter{mycounter}
\providecounter{mycounter}

\begin{document}
\end{document}
8
  • 1
    This should IMHO be a standard LaTeX command. +1
    – user194703
    Dec 23, 2019 at 18:22
  • This is helpful although im still not sure it helps my exact situation i think i may have an idea now that u gave me this idea. Dec 23, 2019 at 18:41
  • @JacobHacker You can, of course, redefine LaTeX's \newcounter to behave like that, if the name of the command is the problem, although I recommend you not to do that... Dec 23, 2019 at 18:45
  • 1
    @Schrödinger'scat - Having more than one package using the same counter for different purposes is a recipe for disaster. Dec 23, 2019 at 19:51
  • @JohnKormylo Well, many counters are just dummy counters, I often introduce iloop for \loops, so I'm really glad to see that there is a simple way to define it without getting all the complaints that there is an error. Sure, if you have nothing better to do than calling your "new" counter equation, say, then you are crying for trouble.
    – user194703
    Dec 23, 2019 at 20:01

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .