Error message “invalid escape sequence near ”\%" when tex.sprint is inside a \chapter command

The error message "invalid escape sequence near "\%"" occurs only when a \luaexec tex.sprint is placed inside a \chapter command: why ?

\documentclass{book}
\usepackage{luacode}
\begin{document}

\def\CalculusResult{
\luaexec{Calculus = 1/3 tex.sprint (string.format("\%0.5f", Calculus))}}%

\chapter{\huge When placed inside a chapter command, the  CalculusResult \CalculusResult ~  prints well but produces an error message: invalid escape sequence near "\%" }%

\huge No error message if the CalculusResult \CalculusResult ~ is in the text.

\end{document}


• The command is not robust, use \protect\CalculusResult, or define it with \DeclareRobustCommand or \NewDocumentCommand (from xparse package). – Ulrike Fischer Jun 22 '16 at 15:34

It's not much different from things like \chapter{abc \eqref{def}} (\eqref is one of the few fragile commands).

The macro \luaexec is fragile, so it should be protected; burying it into another command is not sufficient, unless the other command is protected.

\documentclass{book}
\usepackage{luacode}

\newcommand\CalculusResult{%
\luaexec{Calculus = 1/3 tex.sprint (string.format("\%0.5f", Calculus))}%
}

\begin{document}

\tableofcontents

\chapter{When placed inside a chapter command, the
CalculusResult \protect\CalculusResult{} prints
well but produces an error message: invalid escape sequence near "\%"}

No error message if the CalculusResult \CalculusResult{} is in the text.

\end{document}


Note that I have used % in the correct places. You had two in useless ones and missed one in an important place.