0

I'm trying to read a counter value for a specific section. For example

\documentclass{article}
\usepackage{amsmath}

\newcounter{M}[section]
\numberwithin{M}{section}
\newcommand{\foo}{\refstepcounter{M}(\theM)\\}

\begin{document}

\section{First}
\foo
\foo
\foo
\section{Second}
\foo
\foo

\countervalue{M}{1}
\countervalue{M}{2}

\end{document}

I want \countervalue{M}{1} to return 3 and \countervalue{M}{2} to return 2 (or 1.3 and 2.2 respectively), is it possible?

2 Answers 2

1

Okay I've found a simpler way to do it using etoolbox

\documentclass{article}
\usepackage{amsmath}
\usepackage{etoolbox}

\newcounter{M}[section]
\numberwithin{M}{section}
\newcommand{\foo}{
    \refstepcounter{M}
    \csxdef{M\thesection}{\arabic{M}}
    (\theM)\\}

\begin{document}
    \section{First}
    \foo
    \foo
    \foo
    \section{Second}
    \foo
    \foo
    First section has: \csuse{M1} foos\\
    Second section has: \csuse{M2} foos
\end{document}

enter image description here

0

One counter isn't enough because you need to record a different value for each section. Here is one way:

\documentclass{article}
% \usepackage{xparse} % uncomment for LaTeX kernels older than 2020-10-01
\usepackage{etoolbox}

\makeatletter
\NewDocumentCommand{\arystoDef}{s O{section} m}{%
  \newtoggle{arysto@#3@within}%
  \IfBooleanT{#1}% if the starred version was used
    {\toggletrue{arysto@#3@within}%
     \csdef{arysto@#3@parentctr}{#2}% record name of the parent counter for #3
    }%
}

\newcommand*{\arystoIncr}[1]{%
  \edef\arysto@ctrname{arysto@#1@ctr@\number\value{section}}%
  \@ifundefined{c@\arysto@ctrname}
    {\newcounter{\arysto@ctrname}%
     \iftoggle{arysto@#1@within}{%
         \csedef{the\arysto@ctrname}{%
           \arabic{\csuse{arysto@#1@parentctr}}.%
           \unexpanded\expandafter\expandafter\expandafter{%
             \csname the\arysto@ctrname\endcsname}%
         }%
     }{}%
    }{}%
  \refstepcounter{\arysto@ctrname}%
  (\csuse{the\arysto@ctrname})%
}

\newcommand*{\countervalue}[2]{%
  \csuse{thearysto@#1@ctr@#2}%
}
\makeatother

\arystoDef{foo}
\newcommand*{\foo}{\arystoIncr{foo}}

\begin{document}

\section{First}
\foo
\foo
\foo
\section{Second}
\foo
\foo

\bigskip\noindent
\countervalue{foo}{1}\\
\countervalue{foo}{2}

\end{document}

enter image description here

If you use \arystoDef*{foo} or \arystoDef*[section]{foo} instead of \arystoDef{foo}, you'll get this:

enter image description here

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.