[Tex/LaTex] How to use LaTeX commands in a luacode* environment

lualuacode

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

Best Answer

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}
Related Question