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:


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:


But now I get the error:

! Undefined control sequence.

2 Answers 2


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:



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

If you want a real backslash, you can use:

\setmainfont{TeX Gyre Termes} 


  tex.print(-2, "\\");


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).

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .