2

I'm doing

\chapter{chap_one} \newcommand{\chap_oneChapter}{\thechapter}
bla bla bla
\chapter{chap_two} \newcommand{\chap_twoChapter}{\thechapter}
\chap_oneChapter and then \chap_twoChapter

I expected to have printed

1 and then 2

but instead I have

2 and then 2

as if every time LaTeX finds a \chap_oneChapter, it assigns the value of \thechapter, which is not what I wanted. How can I do this correctly?

1 Answers1

7

Are you looking for \label{..} and \ref{..}?

\chapter{chap one vector operators} \label{chap:VectorOperators}
bla bla bla
\chapter{chap two another topic} \label{chap:AnotherTopic}
\ref{chap:VectorOperators} and then \ref{chap:AnotherTopic}

In any case, if that's not what you are looking for…

Roughly you have to expand it, \edef for instance. Note that you can't have _ in the name of commands.

\chapter{chap one vector operators} \edef\VectorOperatorsChapter{\thechapter}
bla bla bla
\chapter{chap two another topic} \edef\AnotherTopicChapter{\thechapter}
\VectorOperatorsChapter{} and then \AnotherTopicChapter

This might give problems at some point, you would need \protected@edef to be secure. So you might want to define

\makeatletter
\newcommand\savevalue[2]{\protected@edef#1{#2}}
\makeatletter

and then use like \savevalue\AnotherTopicChapter{\thechapter}.

Manuel
  • 27,118
  • What is the difference between \def and \edef? And no, \label and \ref are not what I'm looking for, actually I'll use this variables I'm trying to define inside some sort of \ref. – Bruno Murino Sep 26 '16 at 03:42
  • @BrunoMurino -- Maybe you want to look at this answer: http://tex.stackexchange.com/a/519/8528 (there's actually a few good \edef questions on this site). – jon Sep 26 '16 at 04:36
  • 1
    @BrunoMurino \edef expands its contents at the moment of definition. If you defined with \def (or \newcommand) the only thing you are storing is the symbolic \thechapter so it expands to its value later rather than at the point of definition. In any case, you can still label de chapter and do \def\VectorOperatorsChapter{\ref{chap:VectorOperators}} and use \VectorOperatorsChapter and it will work as you expect. – Manuel Sep 26 '16 at 05:10
  • @Manuel Thanks! Everything is working fine now! And thanks for the explanation! – Bruno Murino Sep 26 '16 at 09:57