Hopefully useful example of \directlua{} expansion

The following example may help to understand a little more about \directlua{} expansion.

\documentclass[11pt,twoside]{article}
\begin{document}

\def\xx{Hello}
\def\yy{(}
\def\zz{)}
\newcommand{\hellofromTeX}[1]{

\directlua{

function Hello(str)
tex.print(str)
end

\xx\yy#1\zz
}}

 

\hellofromTeX{"Hello World"}
\end{document}

Here’s how it works.
Code within \directlua{} is expanded according to TeX rules and then sent to the Lua interpreter. In the above, LuaTeX “sees” \xx\yy#1\zz and expands it as follows:


\xx --> Hello
\yy --> (
#1 --> "Hello World"
\zz --> )

After this expansion, the code is fed to the Lua interpreter, which sees Hello("Hello World") and executes


function Hello(str)
tex.print(str)
end

The function tex.print("Hello World") is called and typesets some text.