I have this clumsy code to plot the height of a bouncing ball over time. Is there a possibility for optimization? Perhaps writing the functions directly with the tikz math library? Also at the moment negative time input can't be handled. And how can macros with more then one input argument call lua code?
\documentclass[tikz]{standalone}
\usepackage{fontspec}
\usepackage{pgfplots}
\usepackage{luatextra}
\begin{luacode}
function height(h0, idx)
return h0*(3/4)^(math.abs(idx))
end
function time(h0, idx)
t = math.sqrt(2*height(h0, 0)/9.81)
for i=1,idx,1 do
t = t+2*math.sqrt(2*height(h0, i)/9.81)
end
return t
end
function offset(h0, idx)
o = 0
if idx > 0 then
o = time(h0, idx-1)+(time(h0, idx)-time(h0, idx-1))/2
end
return o
end
\end{luacode}
\makeatletter
\pgfmathdeclarefunction{luaheight}{1}{%
\begingroup
\pgfkeys{/pgf/fpu,/pgf/fpu/output format=sci}%
\pgfmathparse{#1}%
\edef\pgfmathresult{\directlua{tex.print("" .. height(10,\pgfmathresult))}}%
\pgfmathsmuggle\pgfmathresult%
\endgroup
}%
\pgfmathdeclarefunction{luatime}{1}{%
\begingroup
\pgfkeys{/pgf/fpu,/pgf/fpu/output format=sci}%
\pgfmathparse{#1}%
\edef\pgfmathresult{\directlua{tex.print("" .. time(10,\pgfmathresult))}}%
\pgfmathsmuggle\pgfmathresult%
\endgroup
}%
\pgfmathdeclarefunction{luaoffset}{1}{%
\begingroup
\pgfkeys{/pgf/fpu,/pgf/fpu/output format=sci}%
\pgfmathparse{#1}%
\edef\pgfmathresult{\directlua{tex.print("" .. offset(10,\pgfmathresult))}}%
\pgfmathsmuggle\pgfmathresult%
\endgroup
}%
\makeatother
\begin{document}
\begin{tikzpicture}
\begin{axis}
\addplot[domain=0:luatime(0)] {luaheight(0)-9.81/2*x^2};
\foreach \p in {1,...,5} {
\addplot[domain=luatime(\p-1):luatime(\p)] {luaheight(\p)-9.81/2*(x-luaoffset(\p))^2};
}
\end{axis}
\end{tikzpicture}
\end{document}
And it looks like this:


