16

I'm beginning to learn LaTeX and I need some help with counters.

My goal is to store the value a certain counter reaches at some point in the document and use it later. This is my attempt:

\documentclass{article}

\begin{document}

\section{title}

text
\let\myvalue\thesection

\section{title}
text

\myvalue

\end{document}

but \myvalue prints 2 instead of 1.

I read this: What is the difference between \let and \def? but let does not seem to store the value at the definition time in my case.

What am I doing wrong?

  • Well that is expected as you are calling \myvalue after the second section. The declaration \let\myvalue\thesection is just the definition of what \myvalue is. I suppose you want something similar to the referencing command. – azetina Nov 14 '13 at 21:03
  • could you make an example? – Eric Nov 14 '13 at 21:05
  • Welcome to TeX.SX! What do you need \myvalue for? If it's for saying something like “As we say in Section 1”, then you should add \label{sec:whatever} (with a more meaningful string instead of sec:whatever, of course) and say, when you need it, As we saw in Section~\ref{sec:whatever}. – egreg Nov 14 '13 at 21:09
  • I need it to restart the counter from the given value at some later point without having to count how many steps there have been. The proposed solution is more than enough, thank you all. – Eric Nov 14 '13 at 21:15
17

A naive example of how to do that,

\documentclass{article}

\newcounter{foo}

\begin{document}

\section{title}

text
\setcounter{foo}{\value{section}}

\section{title}
text

\thefoo

\end{document}

You just create a new counter with the command \newcounter and you set it to the value you want with \setcounter.

Output

NOTE If you re looking for some referencing tool, better solutions exist with \label{} and \ref{}, among other.

\documentclass{article}

\newcounter{foo}

\begin{document}

\section{title}
\label{sec:mylabel}

text
\setcounter{foo}{\value{section}}

\section{title}

This is using the new counter: \thefoo

\noindent
This is using the label and ref commands: \ref{sec:mylabel}

\end{document}

Output 2

  • yes, this is it. I was sure that I had already tried this! Thanks – Eric Nov 14 '13 at 21:13
11

You can also use \edef but not \def as follows.

\documentclass[preview,border=12pt,varwidth]{standalone}

\begin{document}
\section{Andy}
Saving \ldots
\edef\fixed{\thesection}
\def\notfixed{\thesection}

\section{Billy}
fixed: \fixed\ and notfixed: \notfixed

\section{Charlie}
fixed: \fixed\ and notfixed: \notfixed
\end{document}

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.