2

As in the title. I found from some answers that there seems to be a macro \newluafunction in LaTeX.

However, documentation seems quite sparse...

Screenshot from source2e.pdf

  • What's a "named \luafunction"? Is it expandable/unexpandable/global etc.?
  • What does it mean to define one?
  • How can I use the macro to define a function, then call the function?
user202729
  • 7,143

1 Answers1

5

enter image description here

A wrapper allocating a number to use with \luafunction and \luadef, but possibly not that useful compared to \newluacmd or its Lua equivalent, luatexbase.new_luafunction.

A csname defined via \luadef directly accesses a luatex Lua table of functions, so it is equivalent to using \directlua with a Lua function call, except that it saves an expansion of a macro name, and it saves expanding the argument of \directua as TeX tokens and passing to Lua to be evaluated each time. So \qqq below is \directlua{qqq()} but quicker.

\documentclass{article}

\directlua{ qqqn=0 function qqq () qqqn=qqqn+1 tex.print(qqqn) end } \newluafunction\qqqn

\directlua { local t = lua.get_functions_table() t[\the\qqqn] = qqq }

\luadef\qqq\qqqn

\begin{document}

A: \qqq

B: \qqq

\end{document}

In practice, it would have been better to simply use the size of the lua.get_functions_table() table, rather than a TeX-allocated number, but it seemed a good idea at the time.

See also \newluacmd which was added later which allocates numbers from the same sequence but avoids the need for an extra explicit call to \luadef

\documentclass{article}

\directlua{ qqqn=0 function qqq () qqqn=qqqn+1 tex.print(qqqn) end } \newluacmd\qqq

\directlua { local t = lua.get_functions_table() t[\number\allocationnumber] = qqq }

\begin{document}

A: \qqq

B: \qqq

\end{document}

luatexbase makes the same allocation available from Lua as luatexbase.new_luafunction which saves passing numbers back and forth between TeX and Lua. This defines \qqq to directly refer to the Lua function with all allocation and definition being done in Lua.

\documentclass{article}

\directlua{ qqqn=0 function qqq () qqqn=qqqn+1 tex.print(qqqn) end

local funid= luatexbase.new_luafunction()

lua.get_functions_table()[funid]=qqq token.set_lua('qqq',funid) }

\begin{document}

A: \qqq

B: \qqq

\end{document}

David Carlisle
  • 757,742