3

I am currently exploring ways to generate TikZ code using LuaTeX. Using the luacode* environment seems to be smooth sailing. But sometimes it seems to make more sense to just inject small fragments using Lua into the TikZ environment instead of using hordes of tex.sprint() statements. This seems like a mine field. Given the following MWE:

\documentclass{article}
\usepackage{tikz}
\usepackage{luacode}
\begin{document}    
\begin{tikzpicture}
\luadirect{tex.print("\string\\draw (0,0) to (1,1);")}  % #1 works
\luaexec{tex.print("\\draw (0,0) to (1,1);")}           % #2 works
\draw (0,0) to (\luaexec{tex.sprint("1,1")});           % #3 does not work
\draw (0,0) to (\luadirect{tex.sprint("1,1")});         % #4 works
\draw (0,0) to \luaexec{tex.sprint("(1,1)")};           % #5 doesn't work
\draw (0,0) to \luadirect{tex.sprint("(1,1)")};         % #6 doesn't work
\end{tikzpicture}
\end{document}

Why do #1, #2 and #4 work and #3, #5 and #6 don't?

1

The errors are not directly related to Lua, it is simply a matter of whether tikz is allowing macros or non expandable commands at certain points, you see the same errors for the same reasons with

\documentclass{article}
\usepackage{tikz}

\begin{document}    

\begin{tikzpicture}
\def\zz{\draw (0,0) to (1,1);}\zz           % #1 works
\def\zz{\draw (0,0) to (1,1);}\zz           % #2 works
%\draw (0,0) to (\def\zz{1,1}\zz);           % #3 does not work
\def\zz{1,1}\draw (0,0) to (\zz);           % #4 works
%\draw (0,0) to \def\zz{(1,1)}\zz;           % #5 doesn't work
%\def\zz{(1,1)}\draw (0,0) to \zz;           % #6 doesn't work
\end{tikzpicture}
\end{document}

I find it is often easier to use \directlua (which is expandable) rather than the luacode wrapper which mostly are not expandable as they include catcode assignments to make characters "safe"

| improve this answer | |
  • I was hoping you would answer the question "Using LUA in tikzpicture" with "\tikz{\node{LUA};}", but no.... ;-) – user194703 Nov 20 '19 at 0:40
  • @Schrödinger'scat \begin{picture}\directlua{...} ? – David Carlisle Nov 20 '19 at 0:42
  • The question is "Using LUA in tikzpicture", so no... – user194703 Nov 20 '19 at 0:43
  • @Schrödinger'scat oh you mean like "draw aircraft with tikz" ? – David Carlisle Nov 20 '19 at 0:46
  • Indeed, this one is a great contribution to fight climate change: dysfunctional planes. ;-) – user194703 Nov 20 '19 at 0:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.