# LuaLaTeX output from tex.print not interpreted

This is a follow-up from my previous answer to Automated Creation of Questions and Solutions for a Worksheet/Exam. I realised, that the macros I created like this

\ewcommand{\currentI}{\directlua{tex.print(math.random(1,10)) }}
\newcommand{\turnsN}{\directlua{tex.print(math.random(1,10) * 100) } }


will lead to new values each time I use the macro, therefore are not useful for creating a question and answer as the values will differ.

Upon realising this, I have tried without success to make it work with luacode/luacode* going between [[]], \\ et cetera e.g.

\begin{luacode*}
command_str = "\\newcommand{\\lengthL}{" .. (math.random(1,10)/10) .. "}\n"
print(command_str)
tex.sprint(command_str)
\end{luacode*}


The output from print in the log file returns the string I need e.g.

 \newcommand{\lengthL}{0.7}


but this code does not seem to initialise the variable I need, as I receive a undefined control sequence error, when I try to use \lengthL. I have tried many different ways that I could find in previous answers, but for some reason it eludes me why this is not working.

A full MWE

\documentclass{article}

\usepackage[binary-units]{siunitx}
\usepackage{luacode}

\begin{document}

\begin{luacode*}

-- seed lua PRNG with os time
math.randomseed( os.time() )

command_str = "\\newcommand{\\lengthL}{" .. (math.random(1,10)/10) .. "}\n"
print(command_str)
tex.sprint(command_str)
\end{luacode*}

mean circumference of \SI{\lengthL}{\metre}

\end{document}


You've been bitten by the fact that LaTeX environments form a group, and that includes luacode(*). (Note that the document environment doesn't do this, and one might argue that luacode(*) should not either.) Two possible fixes: use \gdef:

...
command_str = "\\gdef\\lengthL{" .. (math.random(1,10)/10) .. "}\n"
...


or avoid luacode*

\documentclass{article}
\usepackage{siunitx}
\newcommand*\lengthL{}
\directlua{math.randomseed(os.time())}
\edef\lengthL{%
\directlua{tex.print(math.random(1,10)/10)}%
}

\begin{document}
mean circumference of \SI{\lengthL}{\metre}
\end{document}

• @JospehWright Thank you :) I was also missing that \edef expands macros once, which is what I need to create both question and answer consistently wth the same values. – Nils Bausch Jan 27 '16 at 12:44