8

Is it possible to use LuaLaTeX in \pgfmathdeclarefunction?

I tried with sinh which seems to work in pgfmathsetmacro but not in \pgfmathparse and pgfplots. How should I declare a pgf function with Lua correctly?

\documentclass{article}
\usepackage{tikz}
\usepackage{pgfplots}

\makeatletter
\pgfmathdeclarefunction{luasinh}{1}{%
    \begingroup
        \edef\pgfmath@arg{#1}%
        \directlua{tex.setdimen("pgfmath@x", math.sinh(\pgfmath@arg) .. "pt")}%
        \pgfmath@returnone\pgfmath@x%
    \endgroup
}%
\makeatother


\begin{document}

\noindent
Lua: \pgfmathsetmacro\luasinh{luasinh(1)}\luasinh\\
PGF: \pgfmathsetmacro\pgfsinh{sinh(1)}\pgfsinh\\

\begin{tikzpicture}
    \begin{axis}
        \addplot {sinh(x)};
        %\addplot {luasinh(x)}; does not work
    \end{axis}
\end{tikzpicture}

\end{document}

I think being able to use Lua in LuaLaTeX when declaring pgf functions could be useful. For example, this question "Erf function in LaTeX" could maybe be answered without calling Gnuplot but simply call math.erf (if this exists?) in \directlua.

  • 1
    The problem is that pgfplots uses its own internal number format. Put \typeout{#1} into the luasinh definition and you will see stuff like 2Y4.5833334e0] at the terminal. Lua has no idea what to do with that. If you can convert this internal format into a 'normal' number \N then you can just use \edef\pgfmathresult{\directlua{tex.print("" .. math.sinh(\N))}} followed by \pgfmathsmuggle\pgfmathresult\endgroup. – Mark Wibrow Oct 14 '13 at 12:53
5

Based on @Mark Wibrow's comment, I have a working function declaration. The conversion from pgfplots internal syntax to something that is digestable by Lua feels wrong, though:

\documentclass{article}
\usepackage{tikz}
\usepackage{pgfplots}

\makeatletter
\pgfmathdeclarefunction{luasinh}{1}{%
    \begingroup
        \pgfkeys{/pgf/fpu,/pgf/fpu/output format=sci}%
        \pgfmathparse{#1}%
        \edef\pgfmathresult{\directlua{tex.print("" .. math.sinh(\pgfmathresult))}}%
        \pgfmathsmuggle\pgfmathresult%
    \endgroup
}%
\makeatother

\newcommand*\printtest[1]{%
    \section*{Test of $\sinh(#1)$}
    Lua: \directlua{tex.print("" .. math.sinh(#1))}~(directlua)\\
    Lua: \pgfmathsetmacro\luasinh{luasinh(#1)}\luasinh~(luasinh())\\
    Lua: \pgfmathparse{luasinh(#1)}\pgfmathresult~(pgfmathresult)\\
    %PGF: \pgfmathsetmacro\pgfsinh{sinh(#1)}\pgfsinh\\
}%

\begin{document}
\printtest{0}
\printtest{1}
\printtest{10}

\begin{tikzpicture}
    \begin{axis}[domain=-10:10]
        \addplot[mark=o] {sinh(x)};
        \addplot[mark=x] {luasinh(x)}; 
    \end{axis}
\end{tikzpicture}

\end{document}

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.