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}