Error in listings file when combined with \lstset and unicode-math package

It works if you make sure that scriptsize math is set up before listings starts:

enter image description here

\documentclass{article}
\usepackage{unicode-math}
\usepackage{listings}
\lstset{basicstyle=\scriptsize}

\begin{document}
\sbox0{\scriptsize $x$}
\lstinputlisting{test.cpp}
\end{document}

The problem is that fontspec/unicode-math reads font dimens with luacode. And while catcodes in the tex code are frozen when the code is read the first time this is not true for values you get from directlua: there the catcode settings of the execution time matters. So when trying to setup the font in the middle of lstlisting (which activates all chars) things explodes.

A similar problem was here Who's at fault with this error concerning csquotes and LuaLaTeX?

The problem can be resolved by explicitly setting the catcode table in the first argument of tex.sprint when reading the dimens. I added this suggestion to the github tracker of unicode-math.

\documentclass{article}
\usepackage{unicode-math}
\RequirePackage{luacode}
\begin{luacode}
local latexcatcodetable = luatexbase.registernumber("catcodetable@latex")
function fontspec.mathfontdimen(fnt, str)
    local mathdimens = luaotfload.aux.get_math_dimension(fnt, str)
    if mathdimens then
        tex.sprint(latexcatcodetable,mathdimens)
        tex.sprint(latexcatcodetable,"sp")
    else
        tex.sprint(latexcatcodetable,"0pt")
    end
end
\end{luacode}

\usepackage{listings}

\lstset{basicstyle=\scriptsize}
\begin{document}


\begin{lstlisting}
-
\end{lstlisting}

\end{document}