[Tex/LaTex] Lua code with Tikz

lualuatextikz-pgf

Is there a reason why the code below leads to the error:

! Illegal unit of measure (pt inserted).
<to be read again> 
e
l.16 ...t [domain=-.1:.1,samples = 100] (\x,{G(\x)})

\documentclass[tikz]{standalone}
\directlua{
function G (x) 
    return (-(x^2)/3)
end
}
\pgfmathdeclarefunction{G}{1}{%
\edef\pgfmathresult{\directlua{tex.print("" .. G(#1))}}%  
}
\begin{document}
\begin{tikzpicture}
\draw [blue]  plot [domain=-.1:.1,samples = 100] (\x,{G(\x)});
\end{tikzpicture}
\end{document}

Best Answer

If you modify the function to

\pgfmathdeclarefunction{G}{1}{%
\edef\pgfmathresult{\directlua{tex.print("" .. G(#1))}}%  
\show\pgfmathresult
\edef\pgfmathresult{1}%
}

then the plot plots the (wrong:-) function without error but you get to see what you were plotting. The first few values are OK but then:

> \pgfmathresult=macro:
->-9.5052e-06.

Presumably pgf isn't expecting the e notation. Presumably lua has some number formatting functions to prevent it using that notation?

edit ah yes:

\makeatletter
\pgfmathdeclarefunction{G}{1}{%
\edef\pgfmathresult{\directlua{tex.print(string.format("\@percentchar f",G(#1)))}}%  
}
\makeatother
Related Question