[Tex/LaTex] lualatex print, directlua env, and newline

luatex

When using print from lua, if the log file's current line has not been terminated then the lua tex will not start on a new line. This is very annoying because many times I search for some debug string being printed and it is not on a new line but at the end of some rather long line printed from TeX.

e.g.,

Printing some debug string 1
[1{C:/Users/Administrator/AppData/Local/MiKTeX/2.9/pdftex/config/pdftex.map}] 
[2] [3] [4] [5] [6] [7] [8] [9] [10] [11] [12] [13]Printing another debug string 2
[14] [15] [16] [17] [18] [19] [20] [21] [22] [23] [24] [25] [26] [27]`

Instead of

Printing some debug string 1
[1{C:/Users/Administrator/AppData/Local/MiKTeX/2.9/pdftex/config/pdftex.map}] [2] [3] [4] [5] [6] [7] [8] [9] [10] [11] [12] [13]
Printing another debug string 2
[14] [15] [16] [17] [18] [19] [20] [21] [22] [23] [24] [25] [26] [27]

The 2nd one is the preferred case but if I print a newline, \n, then I'll get unnecessary empty lines I do not want.

Is there any way to fix this? Basically on every entry of \directlua or whatever is used I want to print a new line ONLY if something is actually printed(so I don't get a bunch of blank lines) and, even better, only if the log file does not also end on a new line.

Best Answer

Use texio.write_nl(...):

\documentclass{article}
\usepackage{luacode}
\begin{document}
\begin{luacode*}
texio.write_nl("Printing some debug string 1")
\end{luacode*}
foo
\clearpage
\begin{luacode*}
texio.write_nl("Printing some debug string 2")
\end{luacode*}
\end{document}

gives

...
(/opt/texlive2012/texmf-dist/tex/luatex/luatexbase/luatexbase-modutils.sty
(/opt/texlive2012/texmf-dist/tex/luatex/luatexbase/modutils.lua))
(/opt/texlive2012/texmf-dist/tex/luatex/luatexbase/mcb.lua)))) (./test.aux)
Printing some debug string 1 [1{/opt/texlive2012/texmf-var/fonts/map/pdftex/upd
map/pdftex.map}]
Printing some debug string 2 (./test.aux) )
 267 words of node memory still in use:
...

In one project I have defined a helper function:

function w( ... )
  texio.write_nl("-----> " .. string.format(...))
end

so that I can easily use formatted strings:

w("Printing some debug string %d",1)