# LuaLaTeX for dummies: basic directlua use

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?

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}


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}

• thanks, I'll accept it as soon as they let me. Is there any reason for using the starred version of newcommand? – Andreas Hettel Sep 17 '14 at 22:25
• @AndreasHettel Yes, the argument is a number and should not contain paragraphs (\par tokens). – Heiko Oberdiek Sep 17 '14 at 22:27