[Tex/LaTex] How to read a file with luatex

lualuatex

I tried to read a file with lua and set the content as normal text in my document, but I didn't worked it out. Here my code:

\documentclass{scrartcl}
\usepackage{luatextra}
\usepackage{filecontents}

\begin{filecontents}{testdata.dat}
  A  B
  1.0 20
  1.1 21
  1.2 22
\end{filecontents}

\begin{luacode}
  function readtxt()
    file = io.open("testdata.dat", "r")
    text = file:read("*all")
    print(text)
    return tex.print(text) 
  end
\end{luacode}

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

But nothing is printed to the document although lua diplays the content of the file in the terminal.

Best Answer

Edit: a short version of readtxt() function.

\begin{luacode*}
  function readtxt()
    file = io.open("testdata.dat", "r")
    tex.print(string.split(file:read("*a"),"\n"))
  end
\end{luacode*}

First proposition: a solution consists to store lines in a table and to "tex.print" the lines one by one (each argument of tex.print is a single line of TeX).

\documentclass{scrartcl}
\usepackage{luatextra}
\usepackage{filecontents}

\begin{filecontents}{testdata.dat}
  A  B
  1.0 20
  1.1 21
  1.2 22
\end{filecontents}

\begin{luacode}
  function readtxt()
    file = io.open("testdata.dat", "r")
    for line in file:lines() do
      print(line)
      tex.print(line)
    end
  end
\end{luacode}

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