23

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 Answers1

25

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}
Heiko Oberdiek
  • 271,626