# How to use LaTeX commands in a luacode* environment?

How can one access LaTeX commands in the starred version of luacode environment?

I am basically interested in using \ifdefined code below.

For example, this works:

\documentclass{article}
\usepackage{luacode}
%------------------------
\begin{luacode}
function doItOnlyIf(x,y)
\ifdefined\HCode    %will not compile in luacode*
tex.print(x)
\else
tex.print(y)
\fi
end
\end{luacode}
%-------------------
\begin{document}
\directlua{doItOnlyIf("this","that")}
\end{document}

But I need to use luacode* and not luacode (since I have some things that work only in luacode* now).

The above only works in the non-starred version of luacode.

Compiled with lualatex foo.tex and, for tex4ht, compiled using make4ht --lua foo.tex

• the whole point of luacode is to read the argument verbatim so \ works as it works in lua not as it works in TeX, it is often simpler not to use the package at all and just use \directlua{function doItOnlyIf(x,y) \ifdefined\HCode %will not compile in luacode* tex.print(x) \else tex.print(y) \fi end} – David Carlisle May 31 '16 at 6:52

As you've discovered, TeX macros are expanded in a luacode environment but not in a luacode* environment.

If you need to use a luacode* environment, you must check if \HCode is defined outside the luacode* environment, e.g., when calling the Lua function via \directlua.

\documentclass{article}
\usepackage{luacode}
\begin{luacode*}
function doItOnlyIf(x,y,flag)
if flag==1 then
tex.print(x)
else
tex.print(y)
end
end
\end{luacode*}

\newcommand\Hcheck{\ifdefined\HCode1\else0\fi}

\begin{document}
\directlua{doItOnlyIf( "this", "that", \Hcheck )}
\end{document}