4

This question has reference to the question Error with Lua, Luamplib and Mpgraph I am trying to use lua functions inside mplib. The detailed code is here.

\documentclass{article}
\usepackage{luacode}
\usepackage{luamplib}
\begin{document}
\begin{luacode}
  require("math")
   local sin=math.sin;
\end{luacode}
\def\plot{%
  \directlua{
luamplib.process_mplibcode([[
    input graph ;
    beginfig(0)
    draw begingraph(5cm,3cm)
       gdraw (0,sin(0)) for x = 1 upto 3: .. (x, sin(x)) endfor ;
    endgraph ;
    endfig ;
  ]])}%
}
\plot
\end{document}

There seems some problem with intermingling of lua and mplib. Where would be the problem and how can this be corrected?

1
  • What makes you believe that statements within luacode will magically become available inside process_mplibcode? Commented Dec 9, 2019 at 20:28

1 Answer 1

4

You can access Lua from within mplib using the runscript function.

\documentclass{article}
\usepackage{luamplib}
\begin{document}
\def\plot{%
  \directlua{luamplib.process_mplibcode([[
    vardef sin primary x =
        runscript("mp.print(math.sin(" & decimal x & "))")
    enddef ;
    input graph ;
    beginfig(0)
    draw begingraph(5cm,3cm)
       gdraw (0,sin(0)) for x = 1 upto 3: .. (x, sin(x)) endfor ;
    endgraph ;
    endfig ;
  ]])}%
}
\plot
\end{document}

enter image description here

4
  • BTW, if you just want to use sin it's probably shorter to just define vardef sin primary x = sind(x*180/3.1415926) enddef; Commented Dec 9, 2019 at 23:45
  • Is modification possible for standard expressions? For example \plot{sin(x)}, \plot{cos(x)+2} and in general \plot{f(x)} where f(x) is finite combination of some standard functions.
    – user61681
    Commented Jan 15, 2020 at 16:30
  • 1
    @user61681 Yes, that is possible. Commented Jan 16, 2020 at 0:34
  • Thanks for the update.
    – user61681
    Commented Jan 16, 2020 at 1:54

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .