[Tex/LaTex] Printing backslash from a luacode* environment

luatexsymbols

My first attempt with LuaLaTex gave me some headache, trying to generate LaTex code from within LuaLaTex. This required me to print the backslash (to get a LaTeX control sequence).. I think I have found a solution now, but maybe this could also be of interest to others, so I try to post it here as question anyway..

(See also the following questions Printing LaTeX code in LuaTeX and How does one insert a backslash or a tilde into LaTeX?)

From the luacode package documentation, page 2 it says:

The variant luacode* goes further and makes even backslash a normal
character

Consider the following code:

\documentclass{article}
\usepackage{luacode}
\begin{document}
\begin{luacode*}
  tex.sprint("\");
\end{luacode*}
\end{document}

Compiling this with lualatex gives the error

! LuaTeX error <\directlua >:1: unfinished string near '"");'.
\luacode@dbg@exec ...code@maybe@printdbg {#1} #1 }

Then I thought I just have to add another backslash to escape the first:

tex.sprint("\\");

But now I get the error:

! Undefined control sequence.
l.1 

Best Answer

The problem is that there are 3 interpretation stages involved.

  • First macro expansion (this is avoided in my example due to the luacode* environment)
  • Then Lua interprets the resulting string, where a backslash is an escape character
  • At last LaTex again interprets what Lua has printed..

I had forgotten the last stage.. So the solution is:

tex.sprint("$\\backslash$");

or

tex.sprint("\\textbackslash");
Related Question