% language=us runpath=texruns:manuals/luametatex

\environment luametatex-style

\startdocument[title=Metapost]

\startsubject[title=Contents]
    \setups[sectioncontents]
\stopsubject

\startsection[title={Introduction}]

Four letters in the name \LUAMETATEX\ refer to the graphical subsystem \METAPOST,
originally writen by John Hobby as follow up on \METAFONT. This library was
introduced in \LUATEX\ in order to generate graphics runtime instead of via a
separate system call. The library in \LUATEX\ is also used for the stand-alone
program so it has a \POSTSCRIPT\ backend as well as font related frontend. The
version used in \LUAMETATEX\ has neither. The lack of a backend can be explained
from the fact that we have to provide one anyway: the \PDF\ output is generated
by \LUA, which at that time was derived from the converter that I wrote for
\PDFTEX, although there the starting point is the \POSTSCRIPT\ output. Removing
the font related code also makes sense, because in \MKIV\ we never used it: we
need to support \OPENTYPE\ and also want to use properly typeset text so we used
a different approach (\type [option=MP] {textext} and friends).

Another difference with the \LUATEX\ library is that we don't support the binary
number model, which removes a dependency. We kept decimal number support and also
opened that up to the \TEX\ end via \LUA. In addition we support the posit number
model, mostly because we also have that at the \TEX\ end to suit the 32 bit
model. The repertoire of scanners and injectors has been enlarged which makes it
easier and more efficient to interface between the \LUAMETATEX\ subsystems. We
also added functionality to \METAPOST, the language and processor. From the users
perspective the library is downward compatible but at the same time it offers
more.

Just as \LUATEX\ is frozen, the \METAPOST\ library that it uses can be considered
frozen. In \LUAMETATEX\ we have plans for some more extensions. We don't discuss
the already present new functionality here in detail, for that we have separate
manuals, organized under the \LUAMETAFUN\ umbrella. After all, most of what we
did was done in the perspective of using \CONTEXT. Users don't use the functions
discussed below because they only make sense in a more integrated approach as
with \LUAMETAFUN.

\stopsection

\startsection[title={Instances}]

Before you can process \METAPOST\ code an instance needs to be created. There can
be multiple instances active at the same time. They are isolated from each other
so they can use different number models and macro sets. Although you can do
without files, normally you will load (for instance) macros from a file. This
means that we need to interface the library to the file system. If we want to run
\LUA, we need to be able to load \LUA\ code. All this is achieved via callbacks
that have to be set up when an instance is created.

\starttyping[option=LUA]
function mplib.new (
    {
        random_seed    = <t:integer>,
        interaction    = <t:string>,
        job_name       = <t:string>,
        find_file      = <t:function>,
        open_file      = <t:function>,
        run_script     = <t:function>,
        run_internal   = <t:function>,
        make_text      = <t:function>,
        math_mode      = <t:string>,
        utf8_mode      = <t:boolean>,
        text_mode      = <t:boolean>,
        show_mode      = <t:boolean>,
        halt_on_error  = <t:boolean>,
        run_logger     = <t:function>,
        run_overload   = <t:function>,
        run_error      = <t:function>,
        run_warning    = <t:function>,
        bend_tolerance = <t:number>,
        move_tolerance = <t:number>,
    }
)
    return <t:mp>
end
\stoptyping

The library is fed with \METAPOST\ snippets via an \type {execute} function. We
will discuss this in a while.

\starttyping[option=LUA]
function mplib.execute ( <t:mp> instance )
    return <t:table> -- results
end
\stoptyping

An instance can be released with:

\starttyping[option=LUA]
function mplib.finish ( <t:mp> instance )
    return <t:table> -- results
end
\stoptyping

Keeping an instance open is more efficient than creating one per graphic
especially when a format has to be loaded. When you execute code, there can be
results that for instance can be converted into \PDF\ and included in the
currently made document. If one closes an instance it can be that there are
pending results to take care of, although in practice that is unlikely to happen.

When the \type {utf8_mode} parameter is set to \type {true} characters with codes
128 upto 255 can be part of identifiers. There is no checking if we have valid
\UTF\ but it permits to use that encoding. In \CONTEXT, of course, we enable
this. When \type {text_mode} is \type {true} you can use the characters with
\ASCII\ \type {STX} (2) and \type {ETC} (3) to fence string literals so that we
can use double quotes in strings without the need to escape them. The \type
{math_mode} parameter controls the number model that this instance will use.
Valid values are \type {scaled} (default), \type {double} (default in \CONTEXT),
\type {binary} (not supported), \type {decimal} (less performing but maybe
useful) and \type {posit} (so that we can complements the \TEX\ end).

Valid \type {interaction} values are \type {batch}, \type {nonstop}, \type
{scroll}, \type {errorstop} (default) and \type {silent} but in \CONTEXT\ only
the last one makes sense. Setting the \type {random_seed} parameter makes it
possible to reproduce graphics and prevent documents to be different each run
when the size of graphics are different due to randomization. The \type
{job_name} parameter is used in reporting and therefore it is mandate.

Both tolerance parameters default to \im {131 / 65536 = \cldcontext
{"\letterpercent N", 131 / 65536}} and help to make the output smaller: \quote
{bend} relate to straight lines and \quote {move} to effectively similar points.
You can adapt the tolerance any time with:

\starttyping[option=LUA]
function mplib.settolerance (
    <t:mp>     instance,
    <t:number> bendtolerance,
    <t:number> movetolerance
)
    -- no return values
end
\stoptyping

\starttyping[option=LUA]
function mplib.gettolerance ( <t:mp> instance )
    return
        <t:number>, -- bendtolerance
        <t:number>  -- movetolerance
end
\stoptyping

Next we detail the functions that are hooked into the instance because without
them being passed to the engine not that much will happen. We start with the
finder. Here \type {mode} is \type {w} or \type {r}. Normally a lookup of a file
that is to be read from is done by a dedicated lookup mechanism that knows about
the ecosystem the library operates in (like the \TEX\ Directory Structure).

\starttyping[option=LUA]
function find_file (
    <t:string> filename,
    <t:string> mode,
    <t:string> filetype | <t:integer> index
)
    return <t:string> -- foundname
end
\stoptyping

% todo filetype vs index

A (located) file is opened with the \type {open_file} callback that has to
return a table with a \type {close} method and a \type {reader} or a \type
{writer} dependent of the \type {mode}.

\starttyping[option=LUA]
function open_file (
    <t:string> filename,
    <t:string> mode,
    <t:string> filetype | <t:integer> index
)
    return {
        close  = function()
            -- return nothing
        end,
        reader = function()
            return <t:string>
        end,
        writer = function(<t:string>)
            -- return nothing
        end
    }
end
\stoptyping

This approach is not that different from the way we do this at the \TEX\ so like
there a reader normally returns lines. The way \METAPOST\ writes to and read from
files using primitives is somewhat curious which is why the file type can be a
number indicating what handle is used. However, apart from reading files that
have code using \type [option=MP] {input} one hardly needs the more low level
read and write related primitives.

The runner is what makes it possible to communicate between \METAPOST\ and
\LUA\ and thereby \TEX. There are two possible calls:

\starttyping[option=LUA]
function run_script ( <t:string> code | <t:integer> reference )
    return <t:string> metapost
end
\stoptyping

The second approach makes it possible to implement efficient interfaces where
code is turned into functions that are kept around. At the \METAPOST\ end we
therefore have, as in \LUATEX:

\starttyping[option=MP]
runscript "some code that will be loaded and run"
% more code
runscript "some code that will be loaded and run"
\stoptyping

which can of course be optimized by caching, but more interesting is:

\starttyping[option=MP]
newinternal my_function ; my_function := 123 ;
runscript my_function ;
% more code
runscript my_function ;
\stoptyping

which of course has to be dealt with in \LUA. The return value can be a string but also
a direct object:

\starttyping[option=LUA]
function run_script (
    <t:string> code | <t:integer> reference,
    <t:boolean> direct
)
    return
        <t:boolean> | <t:number> | <t:string> | <t:table>, -- result
        <t:boolean>                                        -- success
end
\stoptyping

When the second argument is true, the results are injected directly and tables
become pairs, colors, paths, transforms, depending on how many elements there
are.

In \METAPOST\ internal variables are quantities that are stored a bit differently
and are accessed without using the expression scanner. The \type {run_internal}
function triggers when internal \METAPOST\ variables flagged with \type
{runscript} are initialized, saved or restored. The first argument is an action,
the second the value of internal. When we initialize an internal a third and
fourth argument are passed.

\starttyping[option=LUA]
function run_internal (
    <t:integer> action,
    <t:integer> internal,
    <t:integer> category,
    <t:string>  name
)
    -- no return values
end
\stoptyping

The category is one of the types that \METAPOST\ also uses elsewhere: integer,
boolean, numeric or known. From this you can deduce that internals in \LUAMETATEX\
can not only be numbers but also strings or booleans. The possible actions are:

\ctxlua{moduledata.mplib.codes("getinternalactions")}

There is of course bit extra overhead involved than normal but that can be
neglected especially because we can have more efficient calls to \LUA\ using
references stored in internals. It also has the benefit that one can implement
additional tracing.

\METAPOST\ is a graphic language and system and typesetting text is not what it
is meant for so that gets delegated to (for instance) \TEX\ using \type
[option=MP] {btex} which grabs text upto \type [option=MP] {etex} and passes it
to this callback:

\starttyping[option=LUA]
function make_text ( <t:string> str, <t:integer> mode )
    return <t:string> -- metapost
end
\stoptyping

Here mode is only relevant if you want to intercept \typ {verbatimtex} which is
something that we don't recommend doing in \CONTEXT, just like we don't recommend
using \type [option=MP] {btex}. But, if you use these, keep in mind that spaces
matter. The parameter \type [option=MP] {texscriptmode} controls how spaces and
newlines get honored. The default value is~1. Possible values are:

\starttabulate[|l|p|]
% \DB name      \BC meaning \NC \NR
% \TB
\FL
\BC value      \BC meaning \NC \NR
\ML
\NC \type {0} \NC no newlines \NC \NR
\NC \type {1} \NC newlines in \type [option=MP] {verbatimtex} \NC \NR
\NC \type {2} \NC newlines in \type [option=MP] {verbatimtex} and \type [option=MP] {etex} \NC \NR
\NC \type {3} \NC no leading and trailing strip in \type [option=MP] {verbatimtex} \NC \NR
\NC \type {4} \NC no leading and trailing strip in \type [option=MP] {verbatimtex} and \type [option=MP] {btex} \NC \NR
\LL
\stoptabulate

That way the \LUA\ handler (assigned to \type {make_text}) can do what it likes.
An \type [option=MP] {etex} has to be followed by a space or \type [option=MP]
{;} or be at the end of a line and preceded by a space or at the beginning of a
line. But let's repeat: these commands are kind of old school and not to be used
in \LUAMETAFUN.

Logging, which includes the output of \type {message} and \type {show}, is also
handled by a callback:

\starttyping[option=LUA]
function run_logger ( <t:integer> target, <t:string> str )
    -- no return values
end
\stoptyping

The possible log targets are:

\ctxlua{moduledata.mplib.codes("getlogtargets")}

An overload handler will take care of potentially dangerous overloading of for
instance primitives, macro package definitions and special variables.

\starttyping[option=LUA]
function run_overload ( <t:integer> property, <t:string> name, <t:integer> mode )
    return <t:boolean> -- resetproperty
end
\stoptyping

The \type {mode} value is the currently set \type [option=MP] {overloadmode}
internal. The \METAPOST\ command \typ [option=MP] {setproperty} can be used to
relate an integer value to a quantity and when that value is positive a callback
is triggered when that quantity gets redefined. Primitives get a property value~1
by the engine.

\startluacode
context.starttabulate { "|rT|lT|" }
for k, v in table.sortedhash(mplib.propertycodes) do
    context.NC() context(k)
    context.NC() context(v)
    context.NC() context.NR()
end
context.stoptabulate()
\stopluacode

Overload protect is something very \CONTEXT\ and also present at the \TEX\ end.
All \TEX\ and \METAPOST\ quantities have such properties assigned.

When an error is issued it is often best to just quit the run and fix the issue,
just because the instance can now be in a confused state,

\starttyping[option=LUA]
function run_error (
    <t:string>  message,
    <t:string>  helpinfo,
    <t:integer> interactionmode
)
    -- no return values
end
\stoptyping

You can get some statistics concerning an instance but in practice that is not so
relevant for users. In \CONTEXT\ these go to the log file.

\starttyping[option=LUA]
function mplib.getstatistics ( <t:mp> instance )
    return <t:table>
end
\stoptyping

The next set of numbers reflect for the current state of the \type {metafun:1}
instance that is active for this specific run. Numeric entries are:

\startthreerows
\startluacode
local t = mplib.getstatistics(metapost.getinstancebyname("metafun:1"))
context.starttabulate { "|l|r|" }
    for k, v in table.sortedhash(t) do
        if type(v) ~= "table" then
            context.BC() context(k)
            context.NC() context(v)
            context.NC() context.NR()
        end
    end
context.stoptabulate()
\stopluacode
\stopthreerows

Memory usage is more detailed and comes in sub-tables:

\startluacode
local t = mplib.getstatistics(metapost.getinstancebyname("metafun:1"))
context.starttabulate { "|l|l|r|r|r|r|r|" }
    context.BC()
    context.BC() context("state")
    context.BC() context("kept")
    context.BC() context("max")
    context.BC() context("pool")
    context.BC() context("size")
    context.BC() context("used")
    context.NC() context.NR()
    for k, v in table.sortedhash(t) do
        if type(v) == "table" then
            context.BC() context(k)
            context.NC() context(v.state)
            context.NC() context(v.kept)
            context.NC() context(v.max)
            context.NC() context(v.pool)
            context.NC() context(v.size)
            context.NC() context(v.used)
            context.NC() context.NR()
        end
    end
context.stoptabulate()
\stopluacode

In this version of \MPLIB\ this is informational only. The objects are all
allocated dynamically, so there is no chance of running out of space unless the
available system memory is exhausted. There is no need to configure memory.

The scanner in an instance can be in a specific state:

\starttyping[option=LUA]
function mplib.getstatus ( <t:mp> instance )
    return <t:integer>
end
\stoptyping

where possible states are:

\startfourrows
    \ctxlua{moduledata.mplib.codes("getstates")}
\stopfourrows

Macro names and variable names are stored in a hash table. You can get a list
with entries with \type {gethashentries}, which takes an instance as first
argument. When the second argument is \type {true} more details will be provided.
With \type {gethashentry} you get info about the given macro or variable.

\starttyping[option=LUA]
function mplib.gethashentries ( <t:mp> instance, <t:boolean> details )
    <t:table> hashentries
end
\stoptyping

\starttyping[option=LUA]
function mplib.gethashentry ( <t:mp> instance, <t:string> name )
    return
        <t:integer> -- command
        <t:integer> -- property
        <t:integer> -- subcommand
end
\stoptyping

Say that we have defined:

\starttyping[option=MP]
numeric a ; numeric b ; numeric c ; a = b ; c := b ;
\stoptyping

\startMPcalculation
    numeric a ; numeric b ; numeric c ; a = b ; c := b ;
\stopMPcalculation

We get values like:

\startluacode
local r = {
    { "a",          mplib.gethashentry(metapost.getinstancebyname("metafun:1"),"a") },
    { "b",          mplib.gethashentry(metapost.getinstancebyname("metafun:1"),"b") },
    { "c",          mplib.gethashentry(metapost.getinstancebyname("metafun:1"),"c") },
    { "d",          mplib.gethashentry(metapost.getinstancebyname("metafun:1"),"d") },
    { "def",        mplib.gethashentry(metapost.getinstancebyname("metafun:1"),"def") },
    { "vardef",     mplib.gethashentry(metapost.getinstancebyname("metafun:1"),"vardef") },
    { "fullcircle", mplib.gethashentry(metapost.getinstancebyname("metafun:1"),"fullcircle") },
}
context.starttabulate { "|T|r|r|r|" }
for i=1,#r do
    context.NC() context(r[i][1])
    context.NC() context(r[i][2])
    context.NC() context(r[i][3])
    context.NC() context(r[i][4])
    context.NC() context.NR()
end
context.stoptabulate()
\stopluacode

These numbers represent commands, properties and subcommands, and thereby also
assume some knowledge about how \METAPOST\ works internally. As this kind of
information is only useful when doing low level development we leave it at that.

\stopsection

\startsection[title=Processing]

It is up to the user to decide what to pass to the \type {execute} function as
long as it is valid code. Think of each chunk being a syntactically correct file.
Statements cannot be split over chunks.

\starttyping[option=LUA]
function mplib.execute ( <t:mp> instance, <t:string> code )
    return {
        status = <t:integer>,
        fig    = <t:table>,
    }
end
\stoptyping

In contrast with the normal stand alone \type {mpost} command, there is no
implied \quote {input} at the start of the first chunk. When no string is passed
to the execute function, there will still be one triggered because it then
expects input from the terminal and you can emulate that channel with the
callback you provide. In practice this is not something you need to be worry
about.

When code is fed into the library at some point it will shipout a picture. The
result always has a \type {status} field and an indexed \type {fig} table that
has the graphics produced, although that is not mandate, for instance macro
definitions can happen or variables can be set in which case graphics will be
constructed later.

\starttyping[option=LUA]
<t:userdata> o = <t:mpobj>:objects     ( )
<t:table>    b = <t:mpobj>:boundingbox ( )
<t:number>   w = <t:mpobj>:width       ( )
<t:number>   h = <t:mpobj>:height      ( )
<t:number>   d = <t:mpobj>:depth       ( )
<t:number>   i = <t:mpobj>:italic      ( )
<t:integer>  c = <t:mpobj>:charcode    ( )
<t:number>   t = <t:mpobj>:tolerance   ( )
<t:boolean>  s = <t:mpobj>:stacking    ( )
\stoptyping

When you access a object that object gets processed before its properties are
returned and in the process we loose the original. This means that some
information concerning the whole graphic is also no longer reliably available.
For instance, you can check if a figure uses stacking with the \type {stacking}
function but because objects gets freed after being accessed, no information
about stacking is available then.

The \type {charcode}, \type {width}, \type {height}, \type {depth} and \type
{italic} are a left-over from \METAFONT. They are values of the \METAPOST\
variables \typ [option=MP] {charcode}, \typ [option=MP] {fontcharwd}, \typ
[option=MP] {fontcharht}, \typ [option=MP] {fontchardp} and \typ [option=MP]
{fontcharit} at the time the graphic is shipped out.

You can call \type {fig:objects()} only once for any one \type {fig} object! In
the end the graphic is a list of such userdata objects with accessors that
depends on what specific data we have at hand. You can check out what fields with
the following helper:

\starttyping[option=LUA]
function mplib.getfields ( <t:integer> object | <t:mpobj> object | <t:nil> )
    return <t:table>
end
\stoptyping

You get a simple table with one list of fields, or a table with all possible
fields, organized per object type. In practice this helper is only used for
documentation.

\startluacode
    local t = mplib.getobjecttypes()
    local f = mplib.getfields()
    context.starttabulate { "|lT|lT|plT|" }
    for i=1,#t do
        context.NC() context(i)
        context.NC() context(t[i])
        context.NC() context("% t",f[i])
        context.NC() context.NR()
    end
    context.stoptabulate()
\stopluacode

All graphical objects have a field \type {type} (the second column in the table
above) that gives the object type as a string value. When you have a non circular
pen an envelope is uses defined by \type {path} as well as \type {htap} and the
backend has to make sure that this gets translated into the proper \PDF\
operators. Discussing this is beyond this manual. A \type {color} table has one,
three or four values depending on the color space used. The \typ {prescript} and
\typ {postscript} strings are the accumulated values of these operators,
separated by newline characters. The \typ {stacking} number is just that: a
number, which can be used to put shapes in front or other shapes, some order, but
it depends on the macro package as well as the backend to deal with that; it's
basically just a numeric tag.

Each \type {dash} is a hash with two items. We use the same model as \POSTSCRIPT\
for the representation of the dash list; \type {dashes} is an array of \quote
{on} and \quote {off}, values, and \type {offset} is the phase of the pattern.

There is helper function \type {peninfo} that returns a table containing a bunch
of vital characteristics of the used pen:

\starttyping[option=LUA]
function mplib.peninfo ( <t:mpobj> object )
    return {
        width = <t:number>,
        rx    = <t:number>,
        ry    = <t:number>,
        sx    = <t:number>,
        sy    = <t:number>,
        tx    = <t:number>,
        ty    = <t:number>,
    }
end
\stoptyping

\stopsection

\startsection[title=Internals]

There are a couple of helpers that can be used to query the meaning of specific
codes and states.

\starttyping[option=LUA]
function mplib.gettype ( <mopobj> object )
    return <t:integer> -- typenumber
end
\stoptyping

\starttyping[option=LUA]
function mplib.gettypes ( )
    return <t:table> -- types
end
\stoptyping

\startfourrows
    \ctxlua{moduledata.mplib.codes("gettypes")}
\stopfourrows

\starttyping[option=LUA]
function mplib.getcolormodels ( )
    return <t:table> -- colormodels
end
\stoptyping

\startfourrows
    \ctxlua{moduledata.mplib.codes("getcolormodels")}
\stopfourrows

\starttyping[option=LUA]
function mplib.getcodes ( )
    return <t:table> -- codes
end
\stoptyping

\startfourrows
    \ctxlua{moduledata.mplib.codes("getcodes")}
\stopfourrows

\starttyping[option=LUA]
function mplib.getstates ( )
    return <t:table> -- states
end
\stoptyping

\startfourrows
    \ctxlua{moduledata.mplib.codes("getstates")}
\stopfourrows

Knots is how the \quote {points} in a curve are called internally and in paths we
can find these:

\starttyping[option=LUA]
function mplib.getknotstates ( )
    return <t:table> -- knotstates
end
\stoptyping

\startfourrows
    \ctxlua{moduledata.mplib.codes("getknotstates")}
\stopfourrows

\starttyping[option=LUA]
function mplib.getscantypes ( )
    return <t:table> -- scantypes
end
\stoptyping

\startfourrows
    \ctxlua{moduledata.mplib.codes("getscantypes")}
\stopfourrows

As with \TEX\ we can log to the console, a log file or both. But one will normally
intercept log message anyway.

\starttyping[option=LUA]
function mplib.getlogtargets ( )
    return <t:table> -- logtargets
end
\stoptyping

\startfourrows
    \ctxlua{moduledata.mplib.codes("getlogtargets")}
\stopfourrows

\starttyping[option=LUA]
function mplib.getinternalactions ( )
    return <t:table> -- internalactions
end
\stoptyping

\startfourrows
    \ctxlua{moduledata.mplib.codes("getinternalactions")}
\stopfourrows

\starttyping[option=LUA]
function mplib.getobjecttypes ( )
    return <t:table> -- objecttypes
end
\stoptyping

\startfourrows
    \ctxlua{moduledata.mplib.codes("getobjecttypes")}
\stopfourrows

The next one is of course dependent on what one runs. These statistics are for
all instances:

\starttyping[option=LUA]
function mplib.getcallbackstate ( )
    return <t:table> -- callbackstate
end
\stoptyping

\starttworows
    \ctxlua{moduledata.mplib.codes("getcallbackstate")}
\stoptworows

The text counter is only counting what gets intercepted by \METAPOST\ and as you
can see below, the recommended \type {textext} is handled differently and not
counted at all.

\startlinecorrection
\startcombination[nx=2,ny=1,width=.4tw]
  {\startMPcode
      fill fullcircle xyscaled (4cm,2cm) withcolor "maincolor" ;
      draw textext("okay") withcolor "white" ;
   \stopMPcode} {intercepted by \CONTEXT}
  {\startMPcode
      fill fullcircle xyscaled (4cm,2cm) withcolor "maincolor" ;
      draw btex okay etex withcolor "white" ;
   \stopMPcode} {intercepted by \METAPOST}
\stopcombination
\stoplinecorrection

So we get this now. The file count goes up because from the perspective of
\METAPOST\ code that gets executed and passed as string is just like reading from
file. The relative high number that we see here reflects that we load quite some
\METAFUN\ macros when an instance is initialized.

\startthreerows
    \ctxlua{moduledata.mplib.codes("getcallbackstate")}
\stopthreerows

\stopsection

\startsection[title=Information]

The \METAPOST\ library in \LUATEX\ starts with version~2 so in \LUAMETATEX\ we
start with version~3, assuming that there will me no major update to the older
library.

\starttyping[option=LUA]
function mplib.version ( )
    return <t:string>
end
\stoptyping

When there is an error you can ask for some more context:

\starttyping[option=LUA]
function mplib.showcontext ( <t:mp> instance )
    return <t:string>
end
\stoptyping

\stopsection

\startsection[title=Methods]

For historical reasons we provide a few functions as methods to an instance: \typ
{execute}, \typ {finish}, \typ {getstatistics}, \typ {getstatus} and \typ
{solvepath}, just in case someone goes low level.

\stopsection

\startsection[title=Scanners]

There are quite some scanners available and they all take an instance as first
argument. Some have optional arguments that give some control. A very basic one
is the following. Scanning for a next token in \METAPOST\ is different from \TEX\
because while \TEX\ just gets the token, \METAPOST\ can delay in cases where an
expression is seen. This means that you can inspect what is coming but do some
further scanning based on that. Examples of usage can be found in \CONTEXT\ as it
permits to come up with extensions that behave like new primitives or implement
interfaces that are otherwise hard to do in pure \METAPOST.

\starttyping[option=LUA]
function mplib.scannext ( <t:mp> instance, <t:boolean> keep )
    return <t:integer> token, <t:integer> mode, <t:integer> kind
end
\stoptyping

here the optional \type {keep} boolean argument default to false but when true we
basically have a look ahead scan. Contrary to \TEX\ a next token is not expanded. If we
want to pick up the result from an expression we use the next one where again we can
push back the result:

\startfourrows
    \ctxlua{moduledata.mplib.codes("getscantypes")}
\stopfourrows

\starttyping[option=LUA]
function mplib.scanexpression ( <t:mp> instance, <t:boolean> keep )
    return <t:integer> -- kind
end
\stoptyping

The difference between \typ {scantoken} and \typ {scannext} is that the first one
scans for a token and the later for a value and yes, one has to play a bit with
this to see when one gets what.

\starttyping[option=LUA]
function mplib.scantoken ( <t:mp> instance, <t:boolean> keep )
    return
        <t:integer>, -- token
        <t:integer>, -- mode
        <t:integer>  -- kind
end
\stoptyping

\starttyping[option=LUA]
function mplib.scansymbol ( <t:mp> instance, <t:boolean> expand, <t:boolean> keep )
    return <t:string>
end
\stoptyping

\starttyping[option=LUA]
function mplib.scanproperty ( <t:mp> instance )
    return <t:integer>
end
\stoptyping

These are scanners for the simple data types:

\starttyping[option=LUA]
function mplib.scannumeric ( <t:mp> instance ) return <t:number>  end -- scannumber
function mplib.scaninteger ( <t:mp> instance ) return <t:integer> end
function mplib.scanboolean ( <t:mp> instance ) return <t:boolean> end
function mplib.scanstring  ( <t:mp> instance ) return <t:string>  end
\stoptyping

The scanners that return data types with more than one value can will return a
table when the second argument is \type {true}:

\starttyping[option=LUA]
function mplib.scanpair ( <t:mp> instance, <t:boolean astable )
    return
        <t:number>, -- x
        t:number>   -- y
end
\stoptyping

\starttyping[option=LUA]
function mplib.scancolor (
    <t:mp>      instance,
    <t:boolean astable
)
    return
        <t:number>, -- r
        <t:number>, -- g
        <t:number>  -- b
end
\stoptyping

\starttyping[option=LUA]
function mplib.scancmykcolor ( <t:mp> instance, <t:boolean astable )
    return
        <t:number>, -- c
        <t:number>, -- m
        <t:number>, -- y
        <t:number>  -- k
end
\stoptyping

\starttyping[option=LUA]
function mplib.scantransform ( <t:mp> instance, <t:boolean astable )
    return
        <t:number>, -- x
        <t:number>, -- y
        <t:number>, -- xx
        <t:number>, -- yx
        <t:number>, -- xy
        <t:number>  -- yy
end
\stoptyping

The path scanned is more complex. First an expression is scanned and when okay
it is converted to a table. The compact option gives:

\starttyping[option=LUA]
{
    cycle = <t:boolean>, -- close
    pen   = <t:boolean>,
    {
        <t:number>, -- x_coordinate
        <t:number>, -- y_coordinate
    },
    ...
}
\stoptyping

otherwise we get the more detailed:

\starttyping[option=LUA]
{
    curved = <t:boolean>,
    pen    = <t:boolean>,
    {
        [1]        = <t:number>,  -- x_coordinate
        [2]        = <t:number>,  -- y_coordinate
        [3]        = <t:number>,  -- x_left
        [4]        = <t:number>,  -- y_left
        [5]        = <t:number>,  -- x_right
        [6]        = <t:number>,  -- y_right
        left_type  = <t:integer>,
        right_type = <t:integer>,
        curved     = <t:boolean>,
        state      = <t:integer>,
    },
    ...
}
\stoptyping

Possible (knot, the internal name for a point) states are:

\startfourrows
\ctxlua{moduledata.mplib.codes("getknotstates")}
\stopfourrows

The path scanner function that produces such tables is:

\starttyping[option=LUA]
function mplib.scanpath (
    <t:mp>      instance,
    <t:boolean> compact,
    <t:integer> kind,
    <t:boolean> check
)
    return <t:table>
end
\stoptyping

This pen scanner returns similar tables:

\starttyping[option=LUA]
function mplib.scanpen (
    <t:mp>      instance,
    <t:boolean> compact,
    <t:integer> kind,
    <t:boolean> check
)
    return <t:table>
end
\stoptyping

The next is not really a scanner. It skips a token that matches the given command
and returns a boolean telling if that succeeded.

\starttyping[option=LUA]
function mplib.skiptoken ( <t:mp> instance, <t:integer> command )
    return <t:boolean>
end
\stoptyping

\stopsection

\startsection[title=Injectors]

The scanners are complemented by injectors. Instead of strings that have to be
parsed by \METAPOST\ they inject the right data structures directly.

\starttyping[option=LUA]
function mplib.injectnumeric ( <t:mp> instance, <t:number>  value ) end
function mplib.injectinteger ( <t:mp> instance, <t:integer> value ) end
function mplib.injectboolean ( <t:mp> instance, <t:boolean> value ) end
function mplib.injectstring  ( <t:mp> instance, <t:string>  value ) end
\stoptyping

In following injectors accept a table as well as just the values. which can more
efficient:

\starttyping[option=LUA]
function mplib.injectpair      ( <t:mp> instance, <t:table> value ) end
function mplib.injectcolor     ( <t:mp> instance, <t:table> value ) end
function mplib.injectcmykcolor ( <t:mp> instance, <t:table> value ) end
function mplib.injecttransform ( <t:mp> instance, <t:table> value ) end
\stoptyping

Injecting a path is not always trivial because we have to connect the points
emulating \type [option=MP] {..}, \type [option=MP] {...}, \type [option=MP]
{---} and even \type [option=MP] {&&} and \type [option=MP] {cycle}. A path is
passed as table. The table can be nested and has entries like these:

\starttyping[option=LUA]
{
    {
        x_coord       = <t:number>,
        y_coord       = <t:number>,
        x_left        = <t:number>,
        y_left        = <t:number>,
        x_right       = <t:number>,
        y_right       = <t:number>,
        left_curl     = <t:number>,
        right_curl    = <t:number>,
        left_tension  = <t:number>,
        right_tension = <t:number>,
        direction_x   = <t:number>,
        direction_y   = <t:number>,
    },
    {
        [1] = <t:number>, -- x_coordinate
        [2] = <t:number>, -- x_coordinate
        [3] = <t:number>, -- x_left
        [4] = <t:number>, -- y_left
        [5] = <t:number>, -- x_right
        [6] = <t:number>, -- y_right
    },
    "append",
    "cycle",
}
\stoptyping

Here \type [option=MP] {append} is like \type [option=MP] {&&} which picks up the
pen, and \type [option=MP] {cycle}, not surprisingly, behaves like the \type
[option=MP] {cycle} operator.

\starttyping[option=LUA]
function mplib.injectpath ( <t:mp> instance,  <t:table> value )
    -- return nothing
end
\stoptyping

\starttyping[option=LUA]
function mplib.injectwhatever ( <t:mp> instance, <t:hybrid> value )
    -- return nothing
end
\stoptyping

When a path is entered and has to be injected some preparation takes place out of
the users sight. A special variant of the path processor is the following, where
the path is adapted and the boolean indicates success.

\starttyping[option=LUA]
function mplib.solvepath ( <t:mp> instance, <t:table> value )
    return <t:boolean>
end
\stoptyping

A still somewhat experimental injectors is the following one, that can be used to
fetch information from the \TEX\ end. Valid values for \type {expected} are 1
(integer), 2 (cardinal, 3 (dimension), 5 (boolean) and 7 (string).

\starttyping[option=LUA]
function mplib.expandtex (
    <t:mp>       instance,
    <t:integer>  expected,
    <t:string>   macro,
    <t:whatever> arguments
)
    return <t:whatever>
end
\stoptyping

\stopsection

\stopdocument
