Edit for clarification:
I have a counter whose value I want to write to an aux file. The counter will later be used very dynamically so it has to be read back on subsequent runs or recalculated depending on the need.
The main aim of this question is to figure out how to simply write a counter which gets incremented in a macro to a file.
========
When I run the following MWE the \writeVerse command rightly displays the value of this counter in the PDF output, yet it also adds a bunch of code when I write that counter to a file. Why is this happening?
\documentclass[pagesize=pdftex, fontsize=10]{scrbook}
\newcounter{countVerse}
\newcommand{\writeVerse}{%
\stepcounter{countVerse}%
\thecountVerse%
}
% Write the position to file.
\def\msec@write@lines#1#2{%
\pdfsavepos%
\write\yposoutputfile{%
\string{#1\string}%
\string{#2\string}%
}%
}
\begin{document}
\newwrite\yposoutputfile%
\openout\yposoutputfile=\jobname.ypos.txt%
\writeVerse %this works
\msec@write@lines{1}{F}~Some test text for the first verse.
\msec@write@lines{\writeVerse}{F}~And some more text for the second verse. %this doesn't work EDIT: Added second variable {F}
\closeout\yposoutputfile%
\end{document}
produces this in the output file where the parts in bold should not be present:
{1}{F} {\global \advance \c@countVerse \@ne \relax \begingroup \let \@elt \global \c@ \csname\endcsname\z@ cl@countVerse\endcsname \endgroup 1}{\nobreakspace {}}

\writecarries out expansion and\writeVerseis not expandable. Try\msec@write@lines{\noexpand\writeVerse}to fix this (or at least to avoid the error: not sure what you want!). – Joseph Wright♦ Feb 13 at 16:10