Sometimes you may prefer to use MGL scripts in yours code. It is simpler (especially in comparison with C/Fortran interfaces) and provide faster way to plot the data with annotations, labels and so on. Class mglParse
(see mglParse class parse MGL scripts in C++. It have also the corresponding interface for C/Fortran.
The key function here is mglParse::Parse()
(or mgl_parse()
for C/Fortran) which execute one command per string. At this the detailed information about the possible errors or warnings is passed as function value. Or you may execute the whole script as long string with lines separated by ‘\n’. Functions mglParse::Execute()
and mgl_parse_text()
perform it. Also you may set the values of parameters ‘$0’...‘$9’ for the script by functions mglParse::AddParam()
or mgl_add_param()
, allow/disable picture resizing, check “once” status and so on. The usage is rather straight-forward.
The only non-obvious thing is data transition between script and yours program. There are 2 stages: add or find variable; and set data to variable. In C++ you may use functions mglParse::AddVar()
and mglParse::FindVar()
which return pointer to mglData
. In C/Fortran the corresponding functions are mgl_add_var()
, mgl_find_var()
. This data pointer is valid until next Parse()
or Execute()
call. Note, you must not delete or free the data obtained from these functions!
So, some simple example at the end. Here I define a data array, create variable, put data into it and plot it. The C++ code looks like this:
int sample(mglGraph *gr) { gr->Title("MGL parser sample"); mreal a[100]; // let a_i = sin(4*pi*x), x=0...1 for(int i=0;i<100;i++)a[i]=sin(4*M_PI*i/99); mglParse *parser = new mglParse; mglData *d = parser->AddVar("dat"); d->Set(a,100); // set data to variable parser->Execute(gr, "plot dat; xrange 0 1\nbox\naxis"); // you may break script at any line do something // and continue after that parser->Execute(gr, "xlabel 'x'\nylabel 'y'\nbox"); // also you may use cycles or conditions in script parser->Execute(gr, "for $0 -1 1 0.1\nif $0<0\n" "line 0 0 -1 $0 'r':else:line 0 0 -1 $0 'g'\n" "endif\nnext"); delete parser; return 0; }
The code in C/Fortran looks practically the same:
int sample(HMGL gr) { mgl_title(gr, "MGL parser sample", "", -2); double a[100]; // let a_i = sin(4*pi*x), x=0...1 int i; for(i=0;i<100;i++) a[i]=sin(4*M_PI*i/99); HMPR parser = mgl_create_parser(); HMDT d = mgl_parser_add_var(parser, "dat"); mgl_data_set_double(d,a,100,1,1); // set data to variable mgl_parse_text(gr, parser, "plot dat; xrange 0 1\nbox\naxis"); // you may break script at any line do something // and continue after that mgl_parse_text(gr, parser, "xlabel 'x'\nylabel 'y'"); // also you may use cycles or conditions in script mgl_parse_text(gr, parser, "for $0 -1 1 0.1\nif $0<0\n" "line 0 0 -1 $0 'r':else:line 0 0 -1 $0 'g'\n" "endif\nnext"); mgl_write_png(gr, "test.png", ""); // don't forgot to save picture return 0; }