# Bug in Lualatex: not printing characters from calculation

I have the following code

\documentclass{article}
\usepackage{luacode}
\begin{document}
\begin{luacode*}
local matrix = require "matrix"
local complex = require "complex"
function cmatrix(n)
return matrix(n):replace(complex)
end
function det(m)
tex.sprint(matrix.det(cmatrix(m)))
end
\end{luacode*}
\newcommand{\matrixdet}[1]{\directlua{det(#1)}}
\matrixdet{{{1,2,3},{4,5,6},{"7+8i",8,10}}}
\end{document}


Here I am using matrix.lua and complex.lua from the following links.

https://github.com/davidm/lua-matrix/blob/master/lua/matrix.lua

https://github.com/davidm/lua-matrix/blob/master/lua/complex.lua

The expected answer is -3-24i. However it gives the answer -3-24. The character i is not printed. This works well in lua itself. But it seems to be a bug in lualatex. How can it be over come? Any help will be appreciated.

• copy matrix.lua and complex.lua from the given links to the working folder. Then compile with lualatex. – user61681 Jul 24 '19 at 14:26
• Rather than a bug in LuaTeX, I'd suspect a bug in complex.lua first. – egreg Jul 24 '19 at 14:27

There seems to be an issue in how tex.sprint interprets complex numbers. As a solution, you can convert it to a string before printing:

\documentclass{article}
\usepackage{luacode}
\begin{document}
\begin{luacode*}
local matrix = require "matrix"
local complex = require "complex"
function cmatrix(n)
return matrix(n):replace(complex)
end
function det(m)
tex.sprint(tostring(matrix.det(cmatrix(m))))
end
\end{luacode*}
\newcommand{\matrixdet}[1]{\directlua{det(#1)}}
\matrixdet{{{1,2,3},{4,5,6},{"7+8i",8,10}}}
\end{document}

• Thanks for fast and correct explanation. – user61681 Jul 24 '19 at 14:30

Unlike the Lua print function, which implicitly applies tostringto its argument, tex.sprint is defined to print each entry of a table separately if its argument is a table. The complex number is a two item table with the real and imaginary part with a custom tostring function that adds the i.

So print(matrix.det(cmatrix(m))) invokes tostring and prints -3-24i but tex.sprint applies the normal numeric tostring to each element of the table separately so prints -3 then -24. If you explicitly apply tostring before calling tex.sprint then the function specified for the complex number table will be used, resulting in "-3-24i" again.

• In Lua 5.4 print no longer calls tostring, but instead uses luaL_tolstring. This is functionally very similar to the old behaviour but overriding tostring will no longer work with print. Instead the __tostring metafunction has to be used. – Henri Menke Aug 14 '19 at 2:13