Use lualatex to create macros
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}
If you only need to export a value as a macro, i.e. a macro without a signature, then you could also use the token
library of LuaTeX. The same as in Joseph's answer applies here: Because luacode*
is grouping you have to add the "global"
specifier.
\documentclass{article}
\usepackage{luacode}
\begin{luacode*}
MyVal = 123
token.set_macro("MyVal",MyVal,"global")
\end{luacode*}
\begin{document}
\MyVal
\end{document}
In ConTeXt MkIV you do not need to declare the control sequence global because here \startluacode ... \stopluacode
is not grouping.
\startluacode
MyVal = 123
token.set_macro("MyVal",MyVal)
\stopluacode
\starttext
\MyVal
\stoptext