6

Let's say that I have a Lua function that prints TeX macros: How can those macros be executed during compilation with LuaLaTeX?

In the following example, I defined a LaTeX macro that should print a table (complete with the tabular environment and the actual body) through multiple tex.print calls:

% compile with LuaLaTeX
\documentclass{article}

\usepackage{array}
\newcommand{\mytable}{%
  \directlua{
    tex.print("\\begin{tabular}{lll}")
    tex.print("1 & a & Test A \\\\")
    tex.print("2 & b & Test B \\\\")
    tex.print("\\end{tabular}")
  }
}

\begin{document}
\mytable
\end{document}

However, this doesn't work. Can this be made to work or is this not the way to go at all?

Note: Actually, I define a Lua function in a myfunc.lua file, then I load it with \directlua{dofile("myfunc.lua")} and then I “pass” it to the LaTeX macro.

Related questions:

  1. How to do a 'printline' in LuaTeX
  2. How to manipulate a multi-line string in luatex?
  3. luatex and starting TeX macros which handle new line characters
8

If using the primitive form you need to remember that like \write macros are expanded while sending to lua so you need

\documentclass{article}

\usepackage{array}
\newcommand{\mytable}{%
  \directlua{
    tex.print("\string\\begin{tabular}{lll}")
    tex.print("1 & a & Test A \string\\\string\\")
    tex.print("2 & b & Test B \string\\\string\\")
    tex.print("\string\\end{tabular}")
  }
}

\begin{document}
\mytable
\end{document}
  • Basically I have to write \string before every macro called in the tex.print statements, is that right? – Pier Paolo Mar 16 '15 at 17:00
  • 2
    @PierPaolo or (simpler) set the \catcode of \ to 12 so the argument is written verbatim, the luacode package has several wrappers to make it easy to control the different syntax conventions when going from tex to lua or lua to tex – David Carlisle Mar 16 '15 at 17:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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