[Tex/LaTex] lualatex and string.format

luatex

I´m doing my first steps with lualatex and don´t understand, why the following code results in an error:

\documentclass[ngerman, pagesize]{scrartcl}
\usepackage{luatextra}

\begin{document}

\directlua{
CumCDP_2012 = 1.00E-6
ICumCDP_WIP_2012 = 2.00E-7
ICumCDP_R = 1.00E-7
ICumCDP = ICumCDP_WIP_2012 + ICumCDP_R 
}

\begin{tabular}{cr}
Summe: & \directlua{tex.sprint(ICumCDP)}\\
Summe: & \directlua{tex.sprint(string.format("%e", 51.2))}\\  % <-- error
\end{tabular}

\end{document}

I would like to get 5.12e01.

Best Answer

With package luatextra you have already loaded package luacode. This package provides help with the dealing of special characters, see its documentation. In this case \luaexec together with \% helps. Inside \luaexec \% is a macro that expands to a harmless percent character. Remember, % is usually the comment character in TeX.

\documentclass[ngerman, pagesize]{scrartcl}
\usepackage{luatextra}

\begin{document}

\directlua{
CumCDP_2012 = 1.00E-6
ICumCDP_WIP_2012 = 2.00E-7
ICumCDP_R = 1.00E-7
ICumCDP = ICumCDP_WIP_2012 + ICumCDP_R
}

\begin{tabular}{cr}
Summe: & \directlua{tex.sprint(ICumCDP)}\\
Summe: & \luaexec{tex.sprint(string.format("\%e", 51.2))}\\             
\end{tabular}

\end{document}

Result

Answer to the comment with \% in \directlua:

I expect that using \% within \directlua will not work any longer with the new LuTeX 0.74 with Lua 5.2. Taco Hoekwater (author of LuaTeX) wrote in the luatex mailing list in January 2013 with subject "About lua 5.2 changes":

But also, the string parser has changed:

Lua 5.1 understands the following backslash escapes:

    \a \b \f \n \r \t \v \\ \' \"
              (these all have their expected C meanings)
    \<LF>     (insert a line feed into the string)
    \<CR>     (internally converted to <LF>, then inserted)
    \<d[dd]>  (1-3 decimal digits, result range is 0-255)

Lua 5.2 adds:

    \z        (skips following whitespace in input)
    \x<xx>    (2 case-insensitive hex digits)

Anything else following a backslash is an error in Lua 5.2,
but was silently ignored in 5.1.

With the standard definition of \% in LaTeX (\chardef), the string would get the percent character with preceding backslash. In Lua 5.1 the backslash would be ignored. However in Lua 5.2 the percent character would be "anything else" causing an error now.

Related Question