[Tex/LaTex] Use lualatex to create macros

luatexmacros

I used the following in the past and it worked:

\documentclass{minimal}
\usepackage{luacode,luatextra}
\begin{document}

\begin{luacode*}
MyVal=123
tex.print("\\def\\MyVal{"..MyVal.."}")
\end{luacode*}

MyVal=\MyVal
\end{document}

and it worked fine.

Today I had to use the same source file and now this bit of code no longer defines a macro that can be called in lualatex, i.e. I now get Undefined command message.

I read the following:
Which Lua environment should I use with LuaTeX (LuaLaTeX)?
and
Create macros inside Lua block

I tried luacode sans and with '*' as well as tex.sprint.

I attempted tex.tprint, but I will have to delve in the documentation about that.

My questions then are:

  1. Has anything changed in the last two months?
  2. How would one do the equivalent of the following in lualatex:

    \def{Myval}{100}
    

I also added \noexpand and changed \\ to \, to no avail.

Best Answer

The luacode* environment forms a group, in common with other LaTeX environments. Thus if you want to use this approach and have the value 'escape' then you will need to use \gdef

\documentclass{article}
\usepackage{luacode,luatextra}
\begin{document}

\begin{luacode*}
MyVal=123
tex.print("\\gdef\\MyVal{"..MyVal.."}")
\end{luacode*}

MyVal=\MyVal
\end{document}

As observed in Which Lua environment should I use with LuaTeX (LuaLaTeX)?, the best plan is to use a separate file and load it without grouping, etc.

\RequirePackage{filecontents}
\begin{filecontents*}{\jobname.lua}
MyVal=123
tex.print("\\def\\MyVal{"..MyVal.."}")
\end{filecontents*}

\documentclass{article}
\begin{document}

\directlua{require("\jobname.lua")}

MyVal=\MyVal
\end{document}
Related Question