Perform and show arithmetic with LuaLaTeX

\documentclass[12pt,a4paper]{article}

\directlua{
  function prod(a,b)
    tex.print("$" .. a .. "\string\\times" .. b .. "=" ..  a*b .. "$")
  end
}

\begin{document}    
  The product of 2 and 3: \directlua{prod(2,3)}.
\end{document}

The product of 2 and 3: 2 × 3 = 6.

One tricky thing is getting the backslash escaping game right: LuaTeX: How to handle a Lua function that prints TeX macros. directlua expands macros before passing them on to Lua, so \times gets messed up. But something like \string\times, which should stop that expansion does not quite work as intended because \t is a special escape for the tab in Lua. Hence we need to escape the backslash there. In Lua you would have to type \\times, but in TeX we need to stop the \\ from being expanded, so we need \string\\times. That is one of the reasons why it is often recommended to use the luacode package or externalise Lua functions into their own .lua files and then load them with dofile or require (see for example How to do a 'printline' in LuaTeX, a bit on dofile and require can be found at LuaLatex: Difference between `dofile` and `require` when loading lua files).

Another thing is that you need .. to concatenate strings.

Finally, you probably want the entire expression in math mode and not just certain bits.

Also moved the \directlua function definition into the preamble. (Thanks to Mico for the suggestion.)


\documentclass[12pt,a4paper]{article}

\begin{document}
    \directlua{
        function prod(a,b)
            tex.print(a.. "$\string\\times$".. b.. "$=$".. a*b)
        end
    }

    The product of 2 and 3: \directlua{prod(2,3)}.
\end{document}

enter image description here


Just for completeness, here's a solution that shows how to (a) write the Lua code to an external file, (b) load the Luacode via a \directlua{dofile("...")} directive, and (c) set up a LaTeX "wrapper" macro (called \showprod in the example below) whose function (pun intended) is to invoke the Lua function.

Note that with this setup, one can write \\ rather than \string\\ to denote a single backslash character. (This is also the case for the luacode and luacode* environments that are provided by the luacode package.)

enter image description here

\RequirePackage{filecontents}
\begin{filecontents*}{show_prod.lua}
function show_prod ( a , b )
  tex.sprint ( "$"..a.."\\times"..b.."="..a*b.."$" )
end
\end{filecontents*}

\documentclass{article}
%% Load Lua code from external file and define a LaTeX "wrapper" macro
\directlua{dofile("show_prod.lua")}
\newcommand\showprod[2]{\directlua{show_prod(#1,#2)}}

\begin{document}
The product of 2 and 3: \showprod{2}{3}.
\end{document}