4

I try to write a setcounter command to a file (using the newfile package) by something like the following

\addtostream{mystream}{\protect\setcounter{mycounter}{\myvariable}}

However, since the whole thing is protected, \myvariable isn't expanded and since it's value changes later in the document, the wrong value ends up in my counter. So, how can I 'unprotect' the variable here?

---EDIT--- Here's the minimal example:

\documentclass{article}

\usepackage{newfile}

\begin{document}
\newoutputstream{stream}
\openoutputfile{stream.file}{stream}

\newcounter{mycounter}
\setcounter{mycounter}{6}

\addtostream{stream}{%
    \protect\setcounter{othercounter}{mycounter}%
}
\closeoutputstream{stream}

\end{document}

It outputs a file called stream.file with the content

\setcounter{othercounter}{mycounter}

but I want

\setcounter{othercounter}{6}
  • Can you please add a minimal example from \documentclass to \end{document}? As far as I know, macros are expanded, which is the reason why \setcounter needs \protect. – egreg Mar 13 '13 at 19:03
  • @egreg I added a minimal example. I hope it is more clear now. – bln-tom Mar 13 '13 at 22:52
  • You have to say \themycounter or \arabic{mycounter} in the \addtostream command. – egreg Mar 13 '13 at 22:52
5

If othercounter and mycounter are LaTeX counters, you can't say

\setcounter{othercounter}{mycounter}

but, in general, you should say

\setcounter{othercounter}{\value{mycounter}}

However, for your application you need a different way, because you need the actual value of mycounter, not referring to the value at the time the assignment is performed. Thus

\addtostream{stream}{%
  \protect\setcounter{othercounter}{\arabic{mycounter}}%
}

is what you're looking for. The write operation will expand \arabic{mycounter} to the current decimal representation of the counter's value.

4

\protect only protects the next token, not the arguments of the next token. If \myvariable is not expanded, then it is perhaps not expandable (e.g. defined by \newcount\myvariable. Then \number helps:

\addtostream{mystream}{%
  \protect\setcounter{mycounter}{\number\myvariable}%
 }%

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.