24

I'm trying to understand the basics of lua programming within LaTeX.

I have this simple function in a file called luatest.lua:

function fact (n)
  if n == 0 then
    return 1
  else
    return n * fact(n-1)
  end
end

Then I have an usual .tex file:

\documentclass{article}

\directlua{dofile("luatest.lua")}
\newcommand{\myluafact}[1]{\directlua{function fact(#1)}}  
\begin{document}
  test \myluafact{5}
\end{document}

Which unfortunately does not compile. It seems to me that I'm missing some tex.sprint() somewhere, but where?

1 Answer 1

26

The function is called fact(#1) without the key word function. Also the result needs to be feed back to TeX, e.g. via tex.write:

\documentclass{article}

\directlua{dofile("luatest.lua")}
\newcommand*{\myluafact}[1]{%
  \directlua{tex.write(fact(#1))}%
}
\begin{document}
  test \myluafact{5}
\end{document}

Result

Improvement for \myluafact: The lua function fact expects a plain integer number, but TeX numbers can come in many different shapes (counters, registers, character constants, ...). If #1 is wrapped inside \numexpr, then even arithmetic calculations are possible:

\documentclass{article}

\directlua{dofile("luatest.lua")}
\newcommand*{\myluafact}[1]{%
  \directlua{tex.write(fact(\the\numexpr(#1)\relax))}%
}
\begin{document}
  test \myluafact{\value{page}+2*2}
\end{document}
2
  • 1
    thanks, I'll accept it as soon as they let me. Is there any reason for using the starred version of newcommand? Sep 17, 2014 at 22:25
  • 2
    @AndreasHettel Yes, the argument is a number and should not contain paragraphs (\par tokens). Sep 17, 2014 at 22:27

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .