# Printing backslash from a luacode* environment

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 \

-

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");

-
Or tex.sprint("\\verb+\\+") depending on the style of backslash you want. –  JLDiaz Mar 16 '13 at 13:04

If you want a real backslash, you can use:

\documentclass{article}
\usepackage{luacode}
\usepackage{fontspec}
\setmainfont{TeX Gyre Termes}

\begin{document}

\begin{luacode*}
tex.print(-2, "\\");
\end{luacode*}

\end{document}


In LuaTeX Reference:

tex.print(<number> n, <string> s, ...)


If n is −2, the resulting catcodes are the result of \the\toks: all category codes are 12 (other) except for the space character, that has category code 10 (space).

-