[Tex/LaTex] How to do a ‘printline’ in LuaTeX

lualuatex

I have just started exploring the world of LuaTeX and wanted to write a piece of code, that prints a name to a new line in the document.

\directlua{
for i=1,3,1 do
tex.print("FOO")
end
}

which should produce the following output:

FOO
FOO
FOO

rather than:

FOO FOO FOO

How do I use Lua correctly? I have tried messing with \\ and many other things over the course of an hour. Am I approaching this problem from the wrong angle? Any help is highly appreciated.

Best Answer

If you are using LaTeX (LuaLaTeX), I'd strongly advice against using \directlua{} for more than a simple call to execute another Lua file. \directlua{} is in no way safe. For example:

  • if you use a Lua comment (--), your code gets Q="!%"§I. This is because in \directlua{} everything is read on one line.
  • If you try to use a literal % sign, for example in tex.print() you... well, try yourself . Good luck.
  • If you try to use an active character such as ~ surprising results are guaranteed.
  • When you want to use tex.print() with a macro, such as \par, you have do crazy stuff to not let TeX see the macro before Lua sees the macro.
  • And good luck inserting strings like "\n" for a new line character.

Now what to do? Use the environment luacode* from the luacode package:

\begin{luacode*}
  for i=1,3,1 do
    tex.print("FOO\\par")
  end  
\end{luacode*}

If you can't use the luacode package (for example when you use plain TeX), use dofile() or require() to load a package and put your code there. TeX can't find and interpret the code there, only Lua. And then you can write

for i=1,3,1 do
  tex.print("FOO\\par")
end

without trouble.