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? Dec 9 '19 at 20:28
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; Dec 9 '19 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
    Jan 15 '20 at 16:30
  • 1
    @user61681 Yes, that is possible. Jan 16 '20 at 0:34
  • Thanks for the update.
    – user61681
    Jan 16 '20 at 1:54

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.