# token.set_macro: \directlua vs. luacode*

If I compile the following code with LuaLaTeX I get the word "RED" as output. The call of token.set_macro inside of luacode* seems to be noneffective.

\listfiles
\documentclass{minimal}
\usepackage{luacode}

\newcommand*\foo{RED}

\iftrue
\begin{luacode*}
token.set_macro('foo', 'GREEN')
\end{luacode*}
\else
\directlua{token.set_macro('foo', 'GREEN')}
\fi

\begin{document}
\foo
\end{document}


After changing \iftrue to \iffalse I get "GREEN". Can anyone explain this behavior? Many thanks.

An environment is a group, if you add a group in the \directlua case, then you see the same:

\listfiles
\documentclass{minimal}
\usepackage{luacode}

\newcommand*\foo{RED}

\iffalse
\begin{luacode*}
token.set_macro('foo', 'GREEN')
\end{luacode*}
\else
{
\directlua{token.set_macro('foo', 'GREEN')}
}
\fi

\begin{document}
\foo
\end{document}

• Oh, so easy is the explanation. I must write token.set_macro('foo', 'GREEN', 'global'). Many thanks, David. – rolfn Dec 12 '18 at 8:24
• @rolfn you could, although personally I'm not convinced by the need for the luacode environments, and I'd probably use \directlua directly. – David Carlisle Dec 12 '18 at 8:57