lualatex-luatextra math mode issue

I'm new here (i.e., pardon my ignorance). But I've been tootling around the LuaLatex and I've come across some bizarre behavior. The following code

\documentclass{article}

\usepackage{luatextra}
\usepackage{xparse}

\begin{luacode*}
function record (m,n)
file = assert(io.open("test2.dat","a"))
file:write(string.format("%s %s",m,n),"\n")
end
\end{luacode*}

\newcounter{prob}
\setcounter{prob}{1}
\DeclareDocumentCommand{\problem}{m}{%
\noindent \textbf{Problem \theprob:} (#1 points)
\directlua{record(\theprob ,#1)} \stepcounter{prob}
}

\begin{document}

$42$

\end{document}


produces the following error:

...MikTex 2.9/tex/luatex/luaotfload/fontloader-2016-06-1 6.lua:10601:
attempt to call field 'suffix' (a nil value).
relax
1.24 $4 2$
?


Here comes the bizarre part. When the above code is augmented to include anything in math mode before the "problem" command is invoked, everything compiles fine. For example

\begin{document}



$42$

\end{document}


compiles with no error. What's the story here? Thanks in advance for your input.

EDIT: The issue appears to have something to do with fontspec since replacing the package luatextra with luacode AND fontspec still exhibits the same behavior.

• Dang. Posted a little too soon. If I replace the luatextra package with luacode everything compiles fine. Perhaps the new question should be why is luatextra being fussy. – Tim Aug 13 '16 at 18:54
• Welcome to TeX.SX. You are free to delete your question if you think that your question doesn't help anybody else. – Stefan Pinnow Aug 13 '16 at 18:56
• Scratch that. The error (and mysterious fix) persists if fontspec is loaded with luacode. So the issue appears to be more with fontspec (since it is loaded with luatextra). – Tim Aug 13 '16 at 19:16

You can cut the example down to

\documentclass{article}

\RequirePackage{fontspec}

\directlua{
function record (m,n)
file = assert(io.open("test2.dat","a"))
end
}

\begin{document}

\directlua{record(1 ,"x")}

$42$

\end{document}


The error is mostly using the variable name file if you change that to

  zzz = assert(io.open("test2.dat","a"))


then it runs without error.

• That works, much obliged! – Tim Aug 13 '16 at 19:34