[Tex/LaTex] How to use mplib directly from lua

graphicsluatexmetapost

I am trying to plot some graphics calling mplib from lualatex.
The 'standard' way is the use of luamplib package and mplibcode environment. I was wandering, is there a way to call mplib from lua directly? As long as mplibcode is just an 'easy' and 'LaTeX' way to do so, it should be possible. However, I could not find any documentation or examples on this topic. Unfortunately, the explanations in the luamplib manual stops at line 54, before I am really able to get an idea of the machinery behind it. It seems that there are few people who knows how to do this, they just had no time to provide others with any documentation.

This thread proposes the solution which seems unnatural: there is lua code which generates tex code inside Tikz environment which is then in turn calls mplib via lua.

Example

The minimal example is:

example.tex:

\documentclass{article}
\usepackage{luamplib}

\begin{document}
\directlua{ dofile('testmplibmin.lua') }
\directlua{ StartMP() }

\end{document}

testmplibmin.lua:

local mpkpse = kpse.new("luatex", "mpost")

local function finder(name, mode, ftype)
  if mode == "w" then
    return name
  else
  return mpkpse:find_file(name,ftype)
  end
end

function StartMP()
  local mplib = require('mplib')
  local mpx=mplib.new({find_file=finder,ini_version=true})
  local result = mpx:execute('input plain;')
  result=mpx:execute('beginfig(1); draw fullcircle scaled 20 withcolor red; endfig;')
  local t,e,l = result.term,result.error,result.log
  if result.status>0 then
    tex.print([[Result of mplib execute is unsuccessfull.]])
  else
    if result.fig then
      tex.sprint('Converted something: \\vrule\\vbox{\\hrule')
      local converted=luamplib.convert(result)
      tex.sprint('\\hrule}\\vrule')
    else
      tex.print([[No figure output.]])
      tex.print([[Log:]])
      tex.print(l)
    end
  end
  mpx:finish()
end

I will try to improve (=shorten) it more. E.g., I believe that there is a way to use finder function from luamplib. Any comments are welcome.

Best Answer

The file mplibapi.pdf from the metapost source distrobution documents the low-level interface. Still, it is probably wise to read the luamplib code as well, because the conversion from mplib's return table (containing images) to PDF literal code is not quite trivial. http://www.tug.org/metapost/src/manual/mplibapi.pdf

Related Question