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.)
\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}
tex.print("$" .. a .. "\string\\times" .. b .. "=" .. a*b .. "$")
a b
is a syntax error (assuminga
andb
are variables). Here,tex.print
is a Lua function that takes a single string as input, so you need to give it a single string. (There are other forms oftex.print
too, that you can read in the LuaTeX manual, but those are probably not what you want.) Lua uses..
to concatenate strings...
, you can also usestring.format
to build a string, e.g. in a filetest.lua
putfunction prod(a,b) tex.print(string.format([[$%d \times %d = %d$]], a, b, a*b)) end
and in your file do\directlua{dofile('test.lua')}
-- here the[[
instead of"
is to avoid needing to escape the backslash in\times
.