[Tex/LaTex] why lua multiline string [[ ]] does not work going from Lua to Latex

lua

lua supports multiline strings.

Mathematica graphics

I need to send such string from Lua back to Latex. I first verified the code works using lua standalone engine

Mathematica graphics

but lualatex does not like something. Here is the MWE

\documentclass[11pt]{article}
\IfFileExists{luatex85.sty}
{\usepackage{luatex85}}{}

\usepackage{amsmath}
\usepackage{luacode}

\begin{luacode}

  function foo(arg)
  local x = [[\\begin{align*}
              x &=y\\\\
              z &=r\\\\
             \\end{align*}
            ]]
  tex.print(x)
  end
\end{luacode}
\begin{document}

\directlua{foo()}
\end{document}

Error is

(/usr/local/texlive/2016/texmf-dist/tex/luatex/ctablestack/ctablestack.sty)))
No file foo7.aux.

! LaTeX Error: There's no line here to end.

See the LaTeX manual or LaTeX Companion for explanation.
Type  H <return>  for immediate help.
 ...                                              

l.22 \directlua{foo()}

? 

It works when printing it on one line as a long string:

\begin{luacode}    
      function foo(arg)
      local x = "\\begin{align*} x &=y\\\\ z &=r\\\\ \\end{align*}"
      tex.sprint(x)
      end
\end{luacode}

It also works if I print each line one by one

\begin{luacode}    
      function foo(arg)      
      tex.print("\\begin{align*}")
      tex.print("x &=y\\\\")
      tex.print("z &=r\\\\")
      tex.print("\\end{align*}")
      end
\end{luacode}

It is easier if one can use the multiline [[ ]] syntax.

Question is: Is it possible to send multiline string from Lua to Latex using [[ .. ]] syntax or must be print each line at a time?

TL 2016

Best Answer

Some remarks:

The following code:

\documentclass[11pt,twocolumn]{article}
\usepackage{amsmath}
\usepackage{luacode}
% \usepackage{fontspec}
\pagestyle{empty}
\begin{luacode*}
  require("lualibs") -- for 'string.split'
  function foo(arg)
  local a = "\\begin{align*} x &=y\\\\ z &=r\\\\ \\end{align*}\\par"
  local b = [[\begin{align*} x &=y\\ z &=r\\ \end{align*}\par]]
  local c = [[\begin{align*}
                x &=y \\
                z &=r \\
              \end{align*}\par]]
  print()
  print(a)
  tex.print(a)
  print(b)
  tex.print(b)
  print(c)
  tex.print(c)
  tex.print(string.split(c,"\n"))
  end
\end{luacode*}

\begin{document}
\directlua{foo()}
\end{document}

produces the following log:

\begin{align*} x &=y\\ z &=r\\ \end{align*}\par
\begin{align*} x &=y\\ z &=r\\ \end{align*}\par
\begin{align*}
x &=y \\
z &=r \\
\end{align*}\par

and the following result:

enter image description here

PS: uncomment \usepackage{fontspec} and the Omega disappears...

Related Question