# LuaTeX: How to handle a Lua function that prints TeX macros

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:

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
• @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