Take the 2-minute tour ×
TeX - LaTeX Stack Exchange is a question and answer site for users of TeX, LaTeX, ConTeXt, and related typesetting systems. It's 100% free, no registration required.

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 \
share|improve this question

2 Answers 2

up vote 5 down vote accepted

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");
share|improve this answer
    
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).

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.