Take the 2-minute tour ×
TeX - LaTeX Stack Exchange is a question and answer site for users of TeX, LaTeX, ConTeXt, and related typesetting systems. It's 100% free, no registration required.

I've written a package that introduces a new environment:

\newfloat{foo}{htb}{bar}[chapter]

The package however can be used for articles, books, ... Since not all of these environments have the concept of chapter, on gets a No counter 'chapter' defined. exception.

How can I check if the chapter counter is defined?

share|improve this question

2 Answers 2

up vote 12 down vote accepted

If a counter foo exists then a count \c@foo exists as well as a macro \thefoo. The \newcounter command (that most likely is used by \newfloat) actually checks if \c@foo exists and calls \@nocounterr{foo} if it doesn't.

The following also checks for \c@foo using etex's \ifcsname ...\endcsname:

\documentclass{article}

\makeatletter
\newcommand*\ifcounter[1]{%
  \ifcsname c@#1\endcsname
    \expandafter\@firstoftwo
  \else
    \expandafter\@secondoftwo
  \fi
}
\makeatother

\begin{document}

Counter \texttt{chapter} \ifcounter{chapter}{exists}{doesn't exist}.

Counter \texttt{section} \ifcounter{section}{exists}{doesn't exist}.

\end{document}

enter image description here

share|improve this answer
1  
\newcommand\ifcounter[3]{\@ifundefined{c@#1}{#3}{#2}} –  egreg Jan 24 at 15:08
1  
@egreg I know :) I just like \ifcsname a tiny bit better since it doesn't leave the command as \relax if it isn't defined –  cgnieder Jan 24 at 15:10
\documentclass{article}
\usepackage{float}
\usepackage{etoolbox}
\ifdef{\thechapter}{\newfloat{foo}{htb}{bar}[chapter]}{}
\begin{document}%
x
\end{document}
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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