[Tex/LaTex] LuaTeX: How to handle a Lua function that prints TeX macros

lualuatexmacros

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

Best Answer

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}
Related Question