# Nesting of functions not working in lualatex

Here is the code. It makes use of the file matrix.lua available at the following link.

\documentclass{article}
\usepackage{luacode}
\begin{document}
\begin{luacode*}
local matrix = require "matrix"
end
function subtract(m,n)
return tex.sprint(matrix.latex(matrix.sub(m,n)))
end
\end{luacode*}
\newcommand{\matrixsubtract}[2]{\directlua{subtract(#1,#2)}}
\def\m{{{1,2,3},{4,5,6},{7,8,9}}}
\def\n{{{2,4,6},{8,10,12},{14,16,20}}}
\matrixsubtract{\m}{\n}\\
\end{document}


These functions work well when called alone. However nesting as in the last line of code does not work. I also know the reason that I am using the function matrix.latex. I think this is the only way to get print output. Is there any way around to get this done?

Note: There is some problem in the matrix.latex function of the file matrix.lua. It prints some unnecessary characters at beginning of each row and in the last entry of the last row of the matrix. I already fixed it. But for this question, it can be neglected.

If you change your add function to

function add(m,n)
end


you will see the problem, you are outputting the wrong string.

the terminal printing will show

$\left( \begin{array}{ccc} 3 & 6 & 9 \\ 12 & 15 & 18 \\ 21 & 24 & 29 \end{array} \right)$


but that is not suitable for your nested calls: you should be outputting the string

     {
{3  , 6 , 9},
{12 ,15 , 18},
{21 , 24 , 29}
}


Something like this, except the matrix library latex print is adding omega for some reason

The basic idea is to generate the Lua input syntax {{1,2,3},{4,5,6}} at all stages except the final call when you generate a latex array.

\documentclass{article}
\usepackage{luacode}
\begin{document}
\begin{luacode*}
local matrix = require "matrix"
end
function subtract(m,n)
tex.sprint(matrixprint(matrix.sub(m,n)))
end
function latex(m)
tex.sprint(matrix.latex(m))
end
function matrixprint (m)
local s=""
if(type(m) == 'table') then
s = s .. "{"
for ii,kk in ipairs(m) do
if ii ~= 1 then
s = s .. ","
end
s = s .. matrixprint(kk)
end
s = s .. "}"
else
s= tostring(m)
end
return s
end
\end{luacode*}

\newcommand\latexmatrix[1]{\directlua{latex(#1)}}

\newcommand{\matrixsubtract}[2]{\directlua{subtract(#1,#2)}}
\def\m{{{1,2,3},{4,5,6},{7,8,9}}}
\def\n{{{2,4,6},{8,10,12},{14,16,20}}}
\latexmatrix{\m}
+
\latexmatrix{\n}
=

\latexmatrix{\m}
-
\latexmatrix{\n}
=
\latexmatrix{\matrixsubtract{\m}{\n}}


• Regarding the omega: the library is obviously giving back a \n, you get an omega too with \fontencoding{OT1}\fontfamily{cmr}\selectfont \directlua{tex.sprint("\string\n abc")}. With unicode-math there is no problem. Jul 25, 2019 at 20:12