Lua in LuaLaTeX

One of the strengths of LuaLaTeX is its ability to call lua code from within tex. Here is a short example on how to do this.

Create a file lib.lua which will contain our lua code. When called from within tex, the function tex.sprint allows to output something into the tex file.

lib.lua

function countlatex(num)
  for i = 1, num do
    tex.sprint(i .. " \\LaTeX, ")
  end
end

In our actual tex file main.tex, we include lib.lua via dofile and then define a macro for the countlatex function.

main.tex

\documentclass{article}

\directlua{dofile("lib.lua")}
\newcommand{\countlatex}[1]{\directlua{countlatex(#1)}}

\begin{document}

\countlatex{5}

\end{document}