Printing newlines using tex.print does not, from TeX's point of view, start new lines but only adds literal line feed tokens. You can avoid that by splitting the line before feeding it to TeX.
This can be done for example using LPEG:
local nl = lpeg.P'\n' -- A newline is a single NL byte. local line = lpeg.C((1-nl)^0) -- A line is a sequence of zero -- or more characters which are not -- newlines ((1-nl)^0) and we use -- lpeg.C to capture the lines -- (aka. return them as results later) -- In total we want zero or more lines followed by newlines and then one -- final line which is not followed by a newline: mfk_splitlines_pattern = (line*nl)^0*line \documentclass{article} \usepackage{tikz} \usepackage{luacode} \begin{luacode*} function MNotWE() local res = [[ \begin{tikzpicture}[fill=blue!20] \path (.2,.8) node {Hello} (.2,.4) node {World}; \end{tikzpicture} ]] return res end function MWE() local res = [[ \begin{tikzpicture}[fill=blue!20] \path (.2,.8) node {Hello} (.2,.4) node {World}; \end{tikzpicture}]] return res end local nl = lpeg.P'\n' local line = lpeg.C((1-nl)^0) mfk_splitlines_pattern = (line*nl)^0*line \end{luacode*} \begin{document} \directlua{tex.print(MWE())} \directlua{tex.print(mfk_splitlines_pattern:match(MNotWE()))} \end{document}