2

I am trying to write a function that would select a text delimited by some symbols (*) from another file and print it. The following gives an error. What is the right way to pass 'text' to string.gsub?

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

\begin{filecontents}{testdata.dat}

  a *string enclosed in* stars

\end{filecontents}

\begin{luacode*}
  function readtxt()
    file = io.open("testdata.dat", "r")
    text = file:read("*all")
    file:close()
    for x in string.gsub(text,"*(.*)*","") do
        tex.print(x)
    end
  end
\end{luacode*}

\begin{document}
  \directlua{readtxt()}
\end{document}
  • Are you sure you want to use *(.*)*? This does not select the literal * which you seemingly want to use as delimiter… – TeXnician Jan 22 at 20:22
2

You need to use gmatch instead of gsub. And probably non greedy regexp (.-) if there are more then one match:

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

\begin{filecontents}{testdata.dat}

  a *string enclosed in* stars *two* 

\end{filecontents}

\begin{luacode*}
  function readtxt()
    file = io.open("testdata.dat", "r")
    text = file:read("*all")
    file:close()
    for x in string.gmatch(text,"*(.-)*") do
        tex.print(x)
    end
  end
\end{luacode*}

\begin{document}
  \directlua{readtxt()}
\end{document}
  • Thank you! To print in lines, how does one insert \par or \n so that Latex correctly transfer it to luacode? tex.print(x)\\par?Obviously tex.print(x)\n does not work since \n = ^^J. – Dmitry Starostin Jan 23 at 6:34
  • tex.print(x .. "\\par") – Denys Potapov Jan 23 at 6:37
  • If I want to include some commands like \footnote into the text processed by lua (I cannot find the answers on this site right now), do I redefine catcode for \ within \begin{luacode*} and then redefine it back within luacode or right after it ends? Is this the 'right' way (and the most direct way)? – Dmitry Starostin Jan 24 at 12:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.