Lua code with Tikz

I would suggest to use Lua for all the calculations and also to create the relevant LaTeX code. Of course as Dave suggested use string.format('% .2f','number') to format the number. Two decimal places would be more than adequate for plotting.

\documentclass[tikz]{standalone}
\usepackage{luacode}
\begin{document}
\begin{luacode}
local function G (x) 
    return string.format('% .2f',-(x^2)/3)
end

tex.print('\\begin{tikzpicture}[scale=.3]')
tex.print('\\draw[color=red] (0,0)')

local z=-.1
for i=1,50 do
   tex.sprint('-- (' .. i .. ',' .. G(z)..')  ') 
   z=z+.2
end
tex.sprint(';')

tex.print('\\end{tikzpicture}')
\end{luacode}
\end{document}

This normally produces cleaner code, is easier to debug and faster. Add formatting code for axes and co-ordinates to suit your requirements. For example using the above it is trivial to also export the values as a table and also do any transformations you may want.


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