# lualatex print, directlua env, and newline

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
[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]


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.

-

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)

-

The way that seems to work really well is to keep track of print a new line initially:

\let\olddirectlua\directlua
\renewcommand{\directlua}[1]{\olddirectlua{print.FirstNewLine = true #1}}


and overload print so the very first time it is used it will print a new line first if FirstNewLine is true(and subsequently make it false). This has the effect of only adding a new line to the log IF text has been added from lua.

print = function (...)
if print.FirstNewLine then rawprint.print("") print.FirstNewLine = false end
rawprint.print(...)
end
`

(rawprint.print is the original print routine)

-