summaryrefslogtreecommitdiff
path: root/doc/context/sources/general/manuals/metafun/metafun-lua.tex
blob: e9e4b4a8d0362f7b2e84643abef5fc80068c9c70 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
% language=us runpath=texruns:manuals/metafun

% this is an extension of about-lua

\startcomponent mfun-lua

\environment metafun-environment

\startchapter[title={Lua}]

\index{\LUA}

\startintro

Already for some years I have been wondering how it would be if we could escape
to \LUA\ inside \METAPOST, or in practice, use \MPLIB\ in \LUATEX. The idea is
simple: embed \LUA\ code in a \METAPOST\ file that gets run as soon as it's seen.
In case you wonder why \LUA\ code makes sense, imagine generating graphics using
external data. The capabilities of \LUA\ to deal with that is more flexible and
advanced than in \METAPOST. Of course we could generate a \METAPOST\ definition
of a graphic from data but often it makes more sense to do the reverse. I finally
found time and reason to look into this and in the following sections I will
describe how it's done.

\blank

{\bi The \LUA\ interface in \MKIV\ is way more limited than in \LMTX\ and new
features will only show up in \LMTX, simply because the \METAPOST\ library in
\LUAMETATEX\ is more powerful.}

\stopintro

% \startsection[title=Introduction]
%
% \stopsection

\startsection[title=The basics]

The approach is comparable to \LUATEX's \type {\directlua}. That primitive can be
used to execute \LUA\ code and in combination with \type {tex.print} we can pipe
back strings into the \TEX\ input stream. There a complication is that that we
have to be able to operate under different so called catcode regimes: the meaning
of characters can differ per regime. We also have to deal with line endings in
special ways as they relate to paragraphs and such. In \METAPOST\ we don't have
that complication so getting back input into the \METAPOST\ input, we can do so
with simple strings. For that a mechanism similar to \type {scantokens} can be
used. That way we can return anything (including nothing) as long as \METAPOST\
can interpret it and as long as it fulfils the expectations.

\starttyping
numeric n ; n := scantokens("123.456") ;
\stoptyping

A script is run as follows:

\starttyping
numeric n ; n := runscript("return '123.456'") ;
\stoptyping

This primitive doesn't have the word \type {lua} in its name so in principle any
wrapper around the library can use it as hook. In the case of \LUATEX\ the script
language is of course \LUA. At the \METAPOST\ end we only expect a string. How
that string is constructed is completely up to the \LUA\ script. In fact, the
user is completely free to implement the runner any way she or he wants, like:

\starttyping
local function scriptrunner(code)
    local f = loadstring(code)
    if f then
        return tostring(f())
    else
        return ""
    end
end
\stoptyping

This is hooked into an instance as follows:

\starttyping
local m = mplib.new {
    ...
    run_script = scriptrunner,
    ...
}
\stoptyping

Now, beware, this is not the \CONTEXT\ way. We provide print functions and other
helpers, which we will explain in the next section.

\stopsection

\startsection[title=Helpers]

After I got this feature up and running I played a bit with possible interfaces
at the \CONTEXT\ (read: \METAFUN) end and ended up with a bit more advanced runner
where no return value is used. The runner is wrapped in the \type {lua} macro.

\startbuffer
numeric n ; n := lua("mp.print(12.34567)") ;
draw textext(n) xsized 4cm withcolor darkred ;
\stopbuffer

\typebuffer

This renders as:

\startlinecorrection[blank]
\processMPbuffer
\stoplinecorrection

In case you wonder how efficient calling \LUA\ is, don't worry: it's fast enough,
especially if you consider suboptimal \LUA\ code and the fact that we switch
between machineries.

\startbuffer
draw image (
    lua("statistics.starttiming()") ;
    for i=1 upto 10000 : draw
        lua("mp.pair(math.random(-200,200),math.random(-50,50))") ;
    endfor ;
    setbounds currentpicture to fullsquare xyscaled (400,100) ;
    lua("statistics.stoptiming()") ;
) withcolor darkyellow withpen pencircle scaled 1 ;
draw textext(lua("mp.print(statistics.elapsedtime())"))
    ysized 50 withcolor darkred ;
\stopbuffer

\typebuffer

Here the line:

\starttyping
draw lua("mp.pair(math.random(-200,200),math.random(-50,50))") ;
\stoptyping

effectively becomes (for instance):

\starttyping
draw scantokens "(25,40)" ;
\stoptyping

which in turn becomes:

\starttyping
draw scantokens (25,40) ;
\stoptyping

The same happens with this:

\starttyping
draw textext(lua("mp.print(statistics.elapsedtime())")) ...
\stoptyping

This becomes for instance:

\starttyping
draw textext(scantokens "1.23") ...
\stoptyping

and therefore:

\starttyping
draw textext(1.23) ...
\stoptyping

We can use \type {mp.print} here because the \type {textext} macro can deal with
numbers. The next also works:

\starttyping
draw textext(lua("mp.quoted(statistics.elapsedtime())")) ...
\stoptyping

Now we get (in \METAPOST\ speak):

\starttyping
draw textext(scantokens (ditto & "1.23" & ditto) ...
\stoptyping

Here \type {ditto} represents the double quotes that mark a string. Of course,
because we pass the strings directly to \type {scantokens}, there are no outer
quotes at all, but this is how it can be simulated. In the end we have:

\starttyping
draw textext("1.23") ...
\stoptyping

What you use, \type {mp.print} or \type {mp.quoted} depends on what the expected
code is: an assignment to a numeric can best be a number or an expression
resulting in a number.

This graphic becomes:

\startlinecorrection[blank]
\processMPbuffer
\stoplinecorrection

The runtime on my current machine is some 0.25 seconds without and 0.12 seconds
with caching. But to be honest, speed is not really a concern here as the amount
of complex \METAPOST\ graphics can be neglected compared to extensive node list
manipulation. With \LUAJITTEX\ generating the graphic takes 15\% less time.

\startbuffer
numeric n ; n := lua("mp.print(1) mp.print('+') mp.print(2)") ;
draw textext(n) xsized 1cm withcolor darkred ;
\stopbuffer

The three print command accumulate their arguments:

\typebuffer

As expected we get:

\startlinecorrection[blank]
\processMPbuffer
\stoplinecorrection

\startbuffer
numeric n ; n := lua("mp.print(1,'+',2)") ;
draw textext(n) xsized 1cm withcolor darkred ;
\stopbuffer

Equally valid is:

\typebuffer

This gives the same result:

\startlinecorrection[blank]
\processMPbuffer
\stoplinecorrection

Of course all kind of action can happen between the prints. It is also legal to
have nothing returned as could be seen in the 10.000 dot example: there the timer
related code returns nothing so effectively we have \type {scantokens("")}. Another
helper is \type {mp.quoted}, as in:

\startbuffer
draw
    textext(lua("mp.quoted('@0.3f'," & decimal 1.234 & ")"))
    withcolor darkred ;
\stopbuffer

\typebuffer

This typesets \processMPbuffer. Watch the \type {@}. When no percent character is
found in the format specifier, we assume that an \type {@} is used instead.

\startbuffer
\startluacode
table.save("demo-data.lua",
    {
        { 1, 2 }, { 2, 4 }, { 3, 3 }, { 4, 2 },
        { 5, 2 }, { 6, 3 }, { 7, 4 }, { 8, 1 },
    }
)
\stopluacode
\stopbuffer

But, the real benefit of embedded \LUA\ is when we deal with data that is stored
at the \LUA\ end. First we define a small dataset:

\typebuffer

\getbuffer

There are several ways to deal with this table. I will show clumsy as well as
better looking ways.

\startbuffer
lua("MP.data = table.load('demo-data.lua')") ;
numeric n ;
lua("mp.print('n := ',\#MP.data)") ;
for i=1 upto n :
    drawdot
        lua("mp.pair(MP.data[" & decimal i & "])") scaled cm
        withpen pencircle scaled 2mm
        withcolor darkred ;
endfor ;
\stopbuffer

\typebuffer

Here we load a \LUA\ table and assign the size to a \METAPOST\ numeric. Next we
loop over the table entries and draw the coordinates.

\startlinecorrection[blank]
\processMPbuffer
\stoplinecorrection

We will stepwise improve this code. In the previous examples we omitted wrapper
code but here we show it:

\startbuffer
\startluacode
    MP.data = table.load('demo-data.lua')
    function MP.n()
        mp.print(#MP.data)
    end
    function MP.dot(i)
        mp.pair(MP.data[i])
    end
\stopluacode

\startMPcode
    numeric n ; n := lua("MP.n()") ;
    for i=1 upto n :
        drawdot
            lua("MP.dot(" & decimal i & ")") scaled cm
            withpen pencircle scaled 2mm
            withcolor darkred ;
    endfor ;
\stopMPcode
\stopbuffer

\typebuffer

So, we create a few helpers in the \type {MP} table. This table is predefined so
normally you don't need to define it. You may however decide to wipe it clean.

\startlinecorrection[blank]
\getbuffer
\stoplinecorrection

You can decide to hide the data:

\startbuffer
\startluacode
    local data = { }
    function MP.load(name)
        data = table.load(name)
    end
    function MP.n()
        mp.print(#data)
    end
    function MP.dot(i)
        mp.pair(data[i])
    end
\stopluacode
\stopbuffer

\typebuffer \getbuffer

It is possible to use less \LUA, for instance in:

\startbuffer
\startluacode
    local data = { }
    function MP.loaded(name)
        data = table.load(name)
        mp.print(#data)
    end
    function MP.dot(i)
        mp.pair(data[i])
    end
\stopluacode

\startMPcode
    for i=1 upto lua("MP.loaded('demo-data.lua')") :
        drawdot
            lua("MP.dot(",i,")") scaled cm
            withpen pencircle scaled 4mm
            withcolor darkred ;
    endfor ;
\stopMPcode
\stopbuffer

\typebuffer

Here we also omit the \type {decimal} because the \type {lua} macro is clever
enough to recognize it as a number.

\startlinecorrection[blank]
\getbuffer
\stoplinecorrection

By using some \METAPOST\ magic we can even go a step further in readability:

\startbuffer
\startMPcode{doublefun}
    lua.MP.load("demo-data.lua") ;

    for i=1 upto lua.MP.n() :
        drawdot
            lua.MP.dot(i) scaled cm
            withpen pencircle scaled 4mm
            withcolor darkred ;
    endfor ;

    for i=1 upto MP.n() :
        drawdot
            MP.dot(i) scaled cm
            withpen pencircle scaled 2mm
            withcolor white ;
    endfor ;
\stopMPcode
\stopbuffer

\typebuffer

Here we demonstrate that it also works ok in \type {double} mode, which makes
much sense when processing data from other sources. Watch how we omit the
type {lua.} prefix: the \type {MP} macro will deal with that.

\startlinecorrection[blank]
\getbuffer
\stoplinecorrection

So in the end we can simplify the code that we started with to:

\starttyping
\startMPcode{doublefun}
    for i=1 upto MP.loaded("demo-data.lua") :
        drawdot
            MP.dot(i) scaled cm
            withpen pencircle scaled 2mm
            withcolor darkred ;
    endfor ;
\stopMPcode
\stoptyping

\stopsection

% \startsection[title=Access to variables]
%
% The question with such mechanisms is always: how far should we go. Although
% \METAPOST\ is a macro language it has properties of procedural languages. It also
% has more introspective features at the user end. For instance, one can loop over
% the resulting picture and manipulate it. This means that we don't need full
% access to \METAPOST\ internals. However, it makes sense to provide access to
% basic variables: \type {numeric}, \type {string}, and \type {boolean}.
%
% \startbuffer
% draw textext(lua("mp.quoted('@0.15f',mp.get.numeric('pi')-math.pi)"))
%     ysized 1cm
%     withcolor darkred ;
% \stopbuffer
%
% \typebuffer
%
% In double mode you will get zero printed but in scaled mode we definitely get a
% difference:
%
% \startlinecorrection[blank]
% \processMPbuffer
% \stoplinecorrection
%
% \startbuffer
% boolean b ; b := true ;
% draw textext(lua("mp.quoted(mp.get.boolean('b') and 'yes' or 'no')"))
%     ysized 1cm
%     withcolor darkred ;
% \stopbuffer
%
% In the next example we use \type {mp.quoted} to make sure that indeed we pass a
% string. The \type {textext} macro can deal with numbers but an unquoted \type
% {yes} or \type {no} is asking for problems.
%
% \typebuffer
%
% Especially when more text is involved it makes sense to predefine a helper in
% the \type {MP} namespace if only because \METAPOST\ (currently) doesn't like
% newlines in the middle of a string, so a \type {lua} call has to be on one line.
%
% \startlinecorrection[blank]
% \processMPbuffer
% \stoplinecorrection
%
% Here is an example where \LUA\ does something that would be close to impossible,
% especially if more complex text is involved.
%
% % \enabletrackers[metapost.lua]
%
% \startbuffer
% string s ; s := "ΤΕΧ" ; % "τεχ"
% draw textext(lua("mp.quoted(characters.lower(mp.get.string('s')))"))
%     ysized 1cm
%     withcolor darkred ;
% \stopbuffer
%
% \typebuffer
%
% As you can see here, the whole repertoire of helper functions can be used in
% a \METAFUN\ definition.
%
% \startlinecorrection[blank]
% \processMPbuffer
% \stoplinecorrection
%
% \stopsection

\startsection[title=The library]

In \CONTEXT\ we have a dedicated runner, but for the record we mention the
low level constructor:

\starttyping
local m = mplib.new {
    ...
    script_runner = function(s) return loadstring(s)() end,
    script_error  = function(s) print(s) end,
    ...,
}
\stoptyping

An instance (in this case \type {m}) has a few extra methods. Instead you can use
the helpers in the library.

\starttabulate[|l|l|]
\HL
\NC \type {m:get_numeric(name)}       \NC returns a numeric (double) \NC \NR
\NC \type {m:get_boolean(name)}       \NC returns a boolean (\type {true} or \type {false}) \NC \NR
\NC \type {m:get_string (name)}       \NC returns a string \NC \NR
\HL
\NC \type {mplib.get_numeric(m,name)} \NC returns a numeric (double) \NC \NR
\NC \type {mplib.get_boolean(m,name)} \NC returns a boolean (\type {true} or \type {false}) \NC \NR
\NC \type {mplib.get_string (m,name)} \NC returns a string \NC \NR
\HL
\stoptabulate

In \CONTEXT\ the instances are hidden and wrapped in high level macros, so there
you cannot use these commands.

\stopsection

\startsection[title=\CONTEXT\ helpers]

The \type {mp} namespace provides the following helpers:

\starttabulate[|l|l|]
\HL
\NC \type {print(...)}                      \NC returns one or more values \NC \NR
\NC \type {fprint(fmt,...)}                 \NC returns a formatted result \NC \NR
\NC \type {boolean(b)}                      \NC returns \type {true} or \type {false} \NC \NR
\NC \type {numeric(f)}                      \NC returns a floating point number \NC \NR
\NC \type {integer(i)}                      \NC returns a whole number \NC \NR
\NC \type {points(i)}                       \NC returns a floating point with unit \type {pt} \NC \NR
\NC \type {pair(x,y)|(t)}                   \NC returns a proper pair \NC \NR
\NC \type {pairpoints(x,y)|(t)}             \NC returns a proper pair with unit \type {pt} \NC \NR
\NC \type {triplet(x,y,z)|(t)}              \NC returns a \RGB\ color \NC \NR
\NC \type {tripletpoints(x,y,z)|(t)}        \NC returns a \RGB\ color but with unit \type {pt} \NC \NR
\NC \type {quadruple(w,x,y,z)|(t)}          \NC returns a \CMYK\ color \NC \NR
\NC \type {quadruplepoints(w,x,y,z)|(t)}    \NC returns a \CMYK\ color but with unit \type {pt} \NC \NR
\NC \type {format(fmt,...)}                 \NC returns a formatted string \NC \NR
\NC \type {quoted(fmt,...)}
    \type {quoted(s)}                       \NC returns a (formatted) quoted string  \NC \NR
\NC \type {path(t[,connect][,close])}       \NC returns a connected (closed) path \NC \NR
\NC \type {pathpoints(t[,connect][,close])} \NC returns a connected (closed) path with units \type {pt} \NC \NR
\HL
\stoptabulate

The \type {mp.get} namespace provides the following helpers:

\starttabulate[|l|l|]
\HL
\NC \type {numeric(name)}      \NC gets a numeric from \METAPOST \NC \NR
\NC \type {boolean(name)}      \NC gets a boolean from \METAPOST \NC \NR
\NC \type {string(name)}       \NC gets a string from \METAPOST \NC \NR
\HL
\stoptabulate

\stopsection

\startsection[title=Paths]

In the meantime we got several questions on the \CONTEXT\ mailing list about turning
coordinates into paths. Now imagine that we have this dataset:

\startbuffer[dataset]
10 20 20 20 -- sample 1
30 40 40 60
50 10

10 10 20 30 % sample 2
30 50 40 50
50 20

10 20 20 10 # sample 3
30 40 40 20
50 10
\stopbuffer

\typebuffer[dataset]

In this case I've put the data in a buffer so that it can be shown
here as well as used in a demo. Watch how we can add comments. The
following code converts this into a table with three subtables.

\startbuffer
\startluacode
  MP.myset = mp.dataset(buffers.getcontent("dataset"))
\stopluacode
\stopbuffer

\typebuffer \getbuffer

We use the \type {MP} (user) namespace to store the table. Next we turn
these subtables into paths:

\startbuffer
\startMPcode
  for i=1 upto lua("mp.print(mp.n(MP.myset))") :
    draw
      lua("mp.path(MP.myset[" & decimal i & "])")
      xysized (HSize-.25ExHeight,10ExHeight)
      withpen pencircle scaled .25ExHeight
      withcolor basiccolors[i]/2 ;
  endfor ;
\stopMPcode
\stopbuffer

\typebuffer

This gives:

\startlinecorrection[blank] \getbuffer \stoplinecorrection

Instead we can fill the path in which case we also need to close it. The
\type {true} argument deals with that:

\startbuffer
\startMPcode
  for i=1 upto lua("mp.print(mp.n(MP.myset))") :
    path p ; p :=
      lua("mp.path(MP.myset[" & decimal i & "],true)")
      xysized (HSize,10ExHeight) ;
    fill p
      withcolor basiccolors[i]/2
      withtransparency (1,.5) ;
  endfor ;
\stopMPcode
\stopbuffer

\typebuffer

We get:

\startlinecorrection[blank] \getbuffer \stoplinecorrection

\startbuffer
\startMPcode
  for i=1 upto lua("mp.print(mp.n(MP.myset))") :
    path p ; p :=
      lua("mp.path(MP.myset[" & decimal i & "])")
      xysized (HSize,10ExHeight) ;
    p :=
      (xpart llcorner boundingbox p,0) --
      p --
      (xpart lrcorner boundingbox p,0) --
      cycle ;
    fill p
      withcolor basiccolors[i]/2
      withtransparency (1,.25) ;
  endfor ;
\stopMPcode
\stopbuffer

The following makes more sense:

\typebuffer

So this gives:

\startlinecorrection[blank] \getbuffer \stoplinecorrection

This (area) fill is so common that we have a helper for it:

\startbuffer
\startMPcode
  for i=1 upto lua("mp.size(MP.myset)") :
    fill area
      lua("mp.path(MP.myset[" & decimal i & "])")
      xysized (HSize,5ExHeight)
      withcolor basiccolors[i]/2
      withtransparency (2,.25) ;
  endfor ;
\stopMPcode
\stopbuffer

\typebuffer

So this gives:

\startlinecorrection[blank] \getbuffer \stoplinecorrection

% A variant call is the following: \footnote {Getting that to work properly in the
% library was non||trivial as the loop variable \type {i} is an abstract nameless
% variable at the \METAPOST\ end. When investigating this Luigi Scarso and I found out
% that the internals of \METAPOST\ are not really geared for interfacing this way
% but in the end it worked out well.}
%
% \startbuffer
% \startMPcode
%   for i=1 upto lua("mp.size(MP.myset)") :
%     fill area
%       lua("mp.path(MP.myset[mp.get.numeric('i')])")
%       xysized (HSize,5ExHeight)
%       withcolor basiccolors[i]/2
%       withtransparency (2,.25) ;
%   endfor ;
% \stopMPcode
% \stopbuffer
%
% \typebuffer
%
% The result is the same:
%
% \startlinecorrection[blank] \getbuffer \stoplinecorrection
%
% \startbuffer
% \startluacode
%   MP.mypath = function(i)
%     return mp.path(MP.myset[mp.get.numeric(i)])
%   end
% \stopluacode
% \stopbuffer
%
% \typebuffer \getbuffer
%
% \startbuffer
% \startMPcode
%   for i=1 upto lua("mp.size(MP.myset)") :
%     fill area
%       lua("MP.mypath('i')")
%       xysized (HSize,5ExHeight)
%       withcolor basiccolors[i]/2
%       withtransparency (2,.25) ;
%   endfor ;
% \stopMPcode
% \stopbuffer
%
% \typebuffer

This snippet of \METAPOST\ code still looks kind of horrible so how can we make
it look better? Here is an attempt, First we define a bit more \LUA:

\startbuffer
\startluacode
local data = mp.dataset(buffers.getcontent("dataset"))

MP.dataset = {
  Line = function(n) mp.path(data[n]) end,
  Size = function()  mp.size(data)    end,
}
\stopluacode
\stopbuffer

\typebuffer \getbuffer

We can now make the \METAPOST\ look more natural. Of course this is possible
because in \METAFUN\ the \type {lua} macro does some extra work.

\startbuffer
\startMPcode
  for i=1 upto lua.MP.dataset.Size() :
    path p ; p :=
      lua.MP.dataset.Line(i)
      xysized (HSize-ExHeight,20ExHeight) ;
    draw
      p
      withpen pencircle scaled .25ExHeight
      withcolor basiccolors[i]/2 ;
    drawpoints
      p
      withpen pencircle scaled ExHeight
      withcolor basiccolors[i]/2 ;
  endfor ;
\stopMPcode
\stopbuffer

\typebuffer

As expected, we get the desired result:

\startlinecorrection[blank] \getbuffer \stoplinecorrection

Once we start making things look nicer and more convenient, we quickly end up
with helpers like the once in the next example. First we save some demo data
in files:

\startbuffer
\startluacode
  io.savedata("foo.tmp","10 20 20 20 30 40 40 60 50 10")
  io.savedata("bar.tmp","10 10 20 30 30 50 40 50 50 20")
\stopluacode
\stopbuffer

\typebuffer \getbuffer

We load the data in datasets:

\startbuffer
\startMPcode
  lua.mp.datasets("load","foo","foo.tmp") ;
  lua.mp.datasets("load","bar","bar.tmp") ;
  fill area
    lua.mp.datasets("foo","line")
    xysized (HSize/2-EmWidth-.25ExHeight,10ExHeight)
    withpen pencircle scaled .25ExHeight
    withcolor darkyellow ;
  fill area
    lua.mp.datasets("bar","line")
    xysized (HSize/2-EmWidth-.25ExHeight,10ExHeight)
    shifted (HSize/2+EmWidth,0)
    withpen pencircle scaled .25ExHeight
    withcolor darkred ;
\stopMPcode
\stopbuffer

\typebuffer

Because the datasets are stored by name we can use them without worrying about
them being forgotten:

\startlinecorrection[blank] \getbuffer \stoplinecorrection

If no tag is given, the filename (without suffix) is used as tag, so the following is
valid:

\starttyping
\startMPcode
  lua.mp.datasets("load","foo.tmp") ;
  lua.mp.datasets("load","bar.tmp") ;
\stopMPcode
\stoptyping

The following methods are defined for a dataset:

\starttabulate[|l|pl|]
\HL
\NC \type {method} \NC usage \NC \NR
\HL
\NC \type {size}   \NC the number of subsets in a dataset \NC \NR
\NC \type {line}   \NC the joined pairs in a dataset making a non|-|closed path \NC \NR
\NC \type {data}   \NC the table containing the data (in subsets, so there is always at least one subset) \NC \NR
\HL
\stoptabulate

{\em In order avoid interference with suffix handling in \METAPOST\ the methods
start with an uppercase character.}

\stopsection

\startsection[title=Passing variables]

You can pass variables from \METAPOST\ to \CONTEXT. Originally that happened via
a temporary file and so called \METAPOST\ specials. Nowadays it's done via \LUA.
Here is an example:

\startbuffer
\startMPcalculation

passvariable("version","1.0") ;
passvariable("number",123) ;
passvariable("string","whatever") ;
passvariable("point",(1.5,2.8)) ;
passvariable("triplet",(1/1,1/2,1/3)) ;
passvariable("quad",(1.1,2.2,3.3,4.4)) ;
passvariable("boolean",false) ;
passvariable("path",fullcircle scaled 1cm) ;
save p ; path p[] ; p[1] := fullcircle ; p[2] := fullsquare ;
passarrayvariable("list",p,1,2,1) ; % first last step
\stopMPcalculation
\stopbuffer

\typebuffer

\getbuffer

We can visualize the result with

\startbuffer
\startluacode
context.tocontext(metapost.variables)
\stopluacode
\stopbuffer

\typebuffer

\getbuffer

In \TEX\ you can access these variables as follows:

\startbuffer
\MPrunvar{version}
\MPruntab{quad}{3}
(\MPrunset{triplet}{,})

$(x,y) = (\MPruntab{point}{1},\MPruntab{point}{2})$
$(x,y) = (\MPrunset{point}{,})$
\stopbuffer

\typebuffer

This becomes: % we need a hack as we cross pages and variables get replace then

\startlines
\getbuffer
\stoplines

Here we passed the code between \type {\startMPcalculation} and \type
{\stopMPcalculation} which does not produce a graphic and therefore takes no
space in the flow. Of course it also works with normal graphics.

\startbuffer
\startMPcode
path p ; p := fullcircle xyscaled (10cm,2cm) ;
path b ; b := boundingbox p ;
startpassingvariable("mypath")
    passvariable("points",p) ;
    startpassingvariable("metadata")
        passvariable("boundingbox",boundingbox p) ;
    stoppassingvariable ;
stoppassingvariable ;
fill p withcolor .625red ;
draw b withcolor .625yellow ;
\stopMPcode
\stopbuffer

\typebuffer

\startlinecorrection[blank]
    \getbuffer
\stoplinecorrection

This time we get:

\ctxlua{context.tocontext(metapost.variables)}

You need to be aware of the fact that a next graphic resets the previous
variables. You can easily overcome that limitation by saving the variables (in
\LUA). It helps that when a page is being shipped out (which can involve
graphics) the variables are protected. You can push and pop variable sets with
\type {\MPpushvariables} and \type {\MPpopvariables}. Because you can nest
the \type {start}||\type{stop} pairs you can create quite complex indexed
and hashed tables. If the results are not what you expect, you can enable a
tracker to follow what gets passed:

\starttyping
\enabletrackers[metapost.variables]
\stoptyping

Serializing variables can be done with the \type {tostring} macro, for instance:

\startbuffer
\startMPcode
message("doing circle",fullcircle);
draw fullcircle ;
\stopMPcode
\stopbuffer

In this case the \type {tostring} is redundant as the message already does the
serialization.

\stopsection

\startsection[title={Interference}]

In this section we will discuss a potential conflict with other mechanisms,
especially primitives and macros. A simple example of using the interface is:

\startbuffer
\startluacode
function MP.AnExample(str)
    mp.aux.quoted(string.reverse(str))
end
\stopluacode

\startMPcode
draw textext(lua.MP.AnExample("Hi there!"))
    rotated 45
    ysized 2cm ;
\stopMPcode
\stopbuffer

\typebuffer

\startlinecorrection
\getbuffer
\stoplinecorrection

The \type {mp} namespace is reserved for functionality provided by \CONTEXT\
itself so you should not polute it with your own code. Instead use the \type {MP}
namespace and mix in some uppercase characters.

Here you see a subnamespace \type {aux} which is where officially the helpers are
organized but they are also accessible directly (as shown in previous sections).
The reason for the \type {aux} namespace is, apart from propection aginst
redefinition, also that we have \type {get} and \type {set} namespaces and there
might be more in the future. At the \LUA\ end you can best use these namespaces
because they are less likely to be accidentally overwritten by user code.

As mentioned, there can still be conflicts. For instance the following will not
work:

\startbuffer
\startluacode
function MP.reverse(str)
    mp.aux.quoted(string.reverse(str))
end
\stopluacode

\startMPcode
draw textext(lua.MP.reverse("Hi there!"))
    rotated -45
    ysized 2cm ;
\stopMPcode
\stopbuffer

\typebuffer

% \startlinecorrection
% \getbuffer
% \stoplinecorrection

The reason is that \type {reverse} gets expanded as part of parsing the macro
name and this command expects an expression. A way out of this is the following:

\startbuffer
\startluacode
function MP.reverse(str)
    mp.aux.quoted(string.reverse(str))
end
\stopluacode

\startMPcode
draw textext(lua.MP("reverse","Hi there!"))
    rotated -45
    ysized 2cm ;
\stopMPcode
\stopbuffer

\typebuffer

\startlinecorrection
\getbuffer
\stoplinecorrection

You can add litle bit of protection for your own code by using a prefix in the
name, like:

\startbuffer
\startluacode
MP["mynamespace.reverse"] = function(str)
    mp.aux.quoted(string.reverse(str))
end
\stopluacode

\startMPcode
draw textext(lua.MP("mynamespace.reverse","Hi there!"))
    rotated -90
    ysized 2cm ;
\stopMPcode
\stopbuffer

\typebuffer

\startlinecorrection
\getbuffer
\stoplinecorrection

\stopsection

\startsection[title=Predefined properties]

As mentioned, the \type {mp} namespace is reserved for commands that come
with the \CONTEXT|-|\METAFUN\ combination. For instance, a lot of layout
related calls are there::

\startcolumns[n=3]
\starttyping
BackSpace
BaseLineSkip
BodyFontSize
BottomDistance
BottomHeight
BottomSpace
CurrentColumn
CurrentHeight
CurrentWidth
CutSpace
EmWidth
ExHeight
FooterDistance
FooterHeight
HeaderDistance
HeaderHeight
InnerEdgeDistance
InnerEdgeWidth
InnerMarginDistance
InnerMarginWidth
LastPageNumber
LayoutColumnDistance
LayoutColumns
LayoutColumnWidth
LeftEdgeDistance
LeftEdgeWidth
LeftMarginDistance
LeftMarginWidth
LineHeight
MakeupHeight
MakeupWidth
NOfColumns
NOfPages
NOfPages
NOfSubPages
OuterEdgeDistance
OuterEdgeWidth
OuterMarginDistance
OuterMarginWidth
PageDepth
PageFraction
PageNumber
PageNumber
PageOffset
PaperBleed
PaperHeight
PaperWidth
PrintPaperHeight
PrintPaperWidth
RealPageNumber
RealPageNumber
RightEdgeDistance
RightEdgeWidth
RightMarginDistance
RightMarginWidth
SpineWidth
StrutDepth
StrutHeight
SubPageNumber
TextHeight
TextWidth
TopDistance
TopHeight
TopSkip
TopSpace
\stoptyping
\stopcolumns

There all return dimensions, contrary to the next few that return a boolean:

\startcolumns[n=3]
\starttyping
OnRightPage
OnOddPage
InPageBody
\stoptyping
\stopcolumns

There are also calls related to backgrounds:

\startcolumns[n=3]
\starttyping
OverlayWidth
OverlayHeight
OverlayDepth
OverlayLineWidth
OverlayOffset
\stoptyping
\stopcolumns

And one related to color:

\startcolumns[n=3]
\starttyping
NamedColor
\stoptyping
\stopcolumns

In most cases such \type {lua.mp.command()} calls have a \METAPOST\ macro with
the same name defined.

\stopsection

\startsection[title=Accessing paths]

A path in \METAPOST\ is internally a linked list of knots and each knot has a
coordinate and two control points. Access to specific points of very large path
can be somewhat slow. First of all, the lookup start at the beginning and when
you use fractions (say halfway between point 4 and 5) the engine has to find the
spot. For this (and other reasons not mentioned here) we have a way to access
paths different, using \LUA\ behind the scenes.

\startbuffer
path p ; p := fullcircle xysized (4cm,2cm) ;
for i inpath p:
    drawdot  leftof i withpen pencircle scaled 2mm withcolor darkred ;
    drawdot pointof i withpen pencircle scaled 3mm withcolor darkgreen ;
    drawdot rightof i withpen pencircle scaled 2mm withcolor darkblue ;
endfor ;
draw for i inpath p:
    pointof i .. controls (leftof i) and (rightof i) ..
endfor cycle withpen pencircle scaled .5mm withcolor white ;

p := p shifted (5cm,0) ;
draw for i inpath p:
    pointof i --
endfor cycle withpen pencircle scaled .5mm withcolor .5white ;
for i inpath p:
    drawdot pointof i withpen pencircle scaled 3mm withcolor darkgreen ;
endfor ;
\stopbuffer

\typebuffer

Here we access the main coordinate and the two control points. The last draw is of course
just mimicking drawing the path.

\startlinecorrection[blank]
\processMPbuffer
\stoplinecorrection

\stopsection

\startsection[title=Acessing \TEX]

In \MKIV\ and \LMTX\ it is possible to access \TEX\ registers and macros from the
\METAPOST\ end. Let's first define and set some:

\startbuffer
\newdimen\MyMetaDimen  \MyMetaDimen = 2mm
\newcount\MyMetaCount  \MyMetaCount = 10
\newtoks \MyMetaToks   \MyMetaToks  = {\bfd \TeX}
     \def\MyMetaMacro                 {not done}
\stopbuffer

\typebuffer \getbuffer

\startbuffer
\startMPcode
    for i=1 upto getcount("MyMetaCount") :
        draw fullcircle scaled (i * getdimen("MyMetaDimen")) ;
    endfor ;
    draw textext(gettoks("MyMetaToks")) xsized 15mm withcolor darkred ;
    setglobaldimen("MyMetaDimen", bbwidth(currentpicture)) ;
    setglobalmacro("MyMetaMacro", "done") ;
\stopMPcode
\stopbuffer

\typebuffer

\startlinecorrection[blank]
    \getbuffer
\stoplinecorrection

We can now look at the two updated globals where \type {\MyMetaMacro: \the\MyMetaDimen}
typesets: {\tttf \MyMetaMacro: \the\MyMetaDimen}. As demonstrated you can best define your
own registers but in principle you can also access system ones, like \type {\scratchdimen}
and friends.

\stopsection

\startsection[title=Abstraction]

We will now stepwise implement some simple helpers for accessing data in files.
The examples are kind of useless but demonstrate how interfaces evolved. The
basic command to communicate with \LUA\ is \type {runscript}. In this example
we will load a (huge) file and run over the lines.

\starttyping
\startMPcode{doublefun}
  save q ; string q ; q := "'\\" & ditto & "'" ;
  runscript (
    "GlobalData = string.splitlines(io.loaddata('foo.tmp')) return ''"
  ) ;
  numeric l ; l = runscript (
    "return string.format('\letterpercent q',\letterhash GlobalData)"
  );
  for i=1 step 1 until l :
    l := length ( runscript (
      "return string.format('\letterpercent q',GlobalData[" & decimal i & "])"
    ) ) ;
  endfor ;
  draw textext(decimal l);
\stopMPcode
\stoptyping

The \type {runscript} primitive takes a string and should return a string (in
\LUAMETATEX\ you can also return nothing). This low level solution will serve as
our benchmark: it takes 2.04 seconds on the rather large (64MB) test file with
10.000 lines.

The code looks somewhat clumsy. This is because in \METAPOST\ escaping is not
built in so one has to append a double quote character using \type {char 34} and
the \type {ditto} string is defined as such. This mess is why in \CONTEXT\ we
have an interface:

\starttyping
\startMPcode{doublefun}
  lua("GlobalData = string.splitlines(io.loaddata('foo.tmp'))") ;
  numeric l ;
  for i=1 step 1 until lua("mp.print(\#GlobalData)") :
    l := length(lua("mp.quoted(GlobalData[" & decimal i & "])")) ;
  endfor ;
  draw textext(decimal l);
\stopMPcode
\stoptyping

As expected we pay a price for the additional overhead, so this time we need 2.28
seconds to process the file. The return value of a run is a string that is fed
into \type {scantokens}. Here \type {print} function prints the number as string
and that gets scanned back to a number. The \type {quoted} function returns a
string in a string so when we're back in \METAPOST\ that gets scanned as string.

When code is used more frequently, we can make a small library, like this:

\starttyping
\startluacode
  local MyData = { }
  function mp.LoadMyData(filename)
    MyData = string.splitlines(io.loaddata(filename))
  end
  local mpprint  = mp.print
  local mpquoted = mp.quoted
  function mp.MyDataSize()
    mpprint(#MyData)
  end
  function mp.MyDataString(i)
    mpquoted(MyData[i] or "")
  end
\stopluacode
\stoptyping

It is not that hard to imagine a more advanced mechanisms where data from multiple
files can be handled at the same time. This code is used as:

\starttyping
\startMPcode{doublefun}
  lua.mp.LoadMyData("foo.tmp") ;
  numeric l ;
  for i=1 step 1 until lua.mp.MyDataSize() :
    l := length(lua.mp.MyDataString(i)) ;
  endfor ;
  draw textext(decimal l);
\stopMPcode
\stoptyping

The \type {mp} namespace at the \LUA\ end is a subnamespace at the \METAPOST\
end. This solution needs 2.20 seconds so we're still slower than the first one,
but in \LUAMETATEX\ with \LMTX we can do better. First the \LUA\ code:

\starttyping
\startluacode
  local injectnumeric = mp.inject.numeric
  local injectstring  = mp.inject.string
  local MyData = { }
  function mp.LoadMyData(filename)
    MyData = string.splitlines(io.loaddata(filename))
  end
  function mp.MyDataSize()
    injectnumeric(#MyData)
  end
  function mp.MyDataString(i)
    injectstring(MyData[i] or "")
  end
\stopluacode
\stoptyping

This time we use injectors. The mentioned \type {print} helpers serialize data so
numbers, pairs, colors etc are converted to a string that represents them that is
fed back to \METAPOST\ after the snippet is run. Multiple prints are collected
into one string. An injecter follows a more direct route: it pushes back a proper
\METAPOST\ data type.

\starttyping
\startMPcode{doublefun}
  lua.mp.LoadMyData("foo.tmp") ;
  numeric l ;
  for i=1 step 1 until lua.mp.MyDataSize() :
    l := length(lua.mp.MyDataString(i)) ;
  endfor ;
  draw textext(decimal l);
\stopMPcode
\stoptyping

This usage brings us down to 1.14 seconds, so we're still not good. The next
variant is performing similar: 1.05 seconds.

\starttyping
\startMPcode{doublefun}
  runscript("mp.LoadMyData('foo.tmp')") ;
  numeric l ;
  for i=1 step 1 until runscript("mp.MyDataSize()") :
    l := length(runscript("mp.MyDataString(" & decimal i & ")")) ;
  endfor ;
  draw textext(decimal l);
\stopMPcode
\stoptyping

We will now delegate scanning to the \LUA\ end.

\starttyping
\startluacode
  local injectnumeric = mp.inject.numeric
  local injectstring  = mp.inject.string
  local scannumeric   = mp.scan.numeric
  local scanstring    = mp.scan.string
  local MyData = { }
  function mp.LoadMyData()
    MyData = string.splitlines(io.loaddata(scanstring()))
  end
  function mp.MyDataSize()
    injectnumeric(#MyData)
  end
  function mp.MyDataString()
    injectstring(MyData[scannumeric()] or "")
  end
\stopluacode
\stoptyping

This time we are faster than the clumsy code we started with: 0.87 seconds.

\starttyping
\startMPcode{doublefun}
  runscript("mp.LoadMyData()") "foo.tmp" ;
  numeric l ;
  for i=1 step 1 until runscript("mp.MyDataSize()") :
    l := length(runscript("mp.MyDataString()") i) ;
  endfor ;
  draw textext(decimal l);
\stopMPcode
\stoptyping

In \LMTX\ we can add some more abstraction. Performance is about the same and
sometimes a bit faster but that depends on extreme usage: you need thousands of
call to notice.

\starttyping
\startluacode
  local injectnumeric = mp.inject.numeric
  local injectstring  = mp.inject.string
  local scannumeric   = mp.scan.numeric
  local scanstring    = mp.scan.string
  local MyData = { }
  metapost.registerscript("LoadMyData", function()
    MyData = string.splitlines(io.loaddata(scanstring()))
  end)
  metapost.registerscript("MyDataSize", function()
    injectnumeric(#MyData)
  end)
  metapost.registerscript("MyDataString", function()
    injectstring(MyData[scannumeric()] or "")
  end)
\stopluacode
\stoptyping

We have the same scripts but we register them. At the \METAPOST\ end we resolve
the registered scripts and then call \type {runscript} with the (abstract) numeric
value:

\starttyping
\startMPcode{doublefun}
  newscriptindex my_script_LoadMyData   ;
  newscriptindex my_script_MyDataSize   ;
  newscriptindex my_script_MyDataString ;

  my_script_LoadMyData   := scriptindex "LoadMyData"   ;
  my_script_MyDataSize   := scriptindex "MyDataSize"   ;
  my_script_MyDataString := scriptindex "MyDataString" ;

  runscript my_script_LoadMyData "foo.tmp" ;
  numeric l ;
  for i=1 step 1 until runscript my_script_MyDataSize :
    l := length(my_script_MyDataString i) ;
  endfor ;
  draw textext(decimal l);
\stopMPcode
\stoptyping

This is of course nicer:

\starttyping
\startMPcode{doublefun}
  def LoadMyData  (expr s) = runscript my_script_LoadMyData   s enddef ;
  def MyDataSize           = runscript my_script_MyDataSize     enddef ;
  def MyDataString(expr i) = runscript my_script_MyDataString i enddef ;

  LoadMyData("foo.tmp") ;
  numeric l ;
  for i=1 step 1 until MyDataSize :
    l := length(MyDataString(i)) ;
  endfor ;
  draw textext(decimal l);
\stopMPcode
\stoptyping

So, to sumarize, there are many ways to look at this: verbose direct ones
but also nicely abstract ones.

\stopsection

% The plugins (like those dealing with text) also use calls in the \type {mp}
% namespace but they have sort of protected names, starting with \type {mf_}. These
% are visible but not meant to be used by users. Not only can their name change,
% their functionality can as well.
%
% The following are actually private as they have related macros but also have a
% public alias:
%
% \startlines
% lua.mp.pathlength(name)
% lua.mp.pathpoint(i)
% lua.mp.pathleft(i)
% lua.mp.pathright(i)
% lua.mp.pathreset()
% \stoplines
%
% They are meant for special high|-|performance path access, for example:
%
% \startlinecorrection
% \startMPcode
%     save p, q, r;
%     path p ; p := for i=1 upto 1000 :
%         (i,0) -- (i,4 + uniformdeviate 4) --
%     endfor cycle ;
%     fill p xysized (TextWidth,20mm) withcolor red ;
%
%     path q ; q := for i=1 upto lua.mp.pathlength("p") :
%         if (i mod 4) == 0 : lua.mp.pathpoint(i) -- fi
%     endfor cycle ;
%     fill q xysized (TextWidth,2cm) shifted (0,-45mm) withcolor green ;
%
%     path r ; r := for i inpath p :
%         if not odd (i) : pointof i -- fi
%     endfor cycle ;
%     fill r xysized (TextWidth,2cm) shifted (0,-70mm) withcolor blue ;
% \stopMPcode
% \stoplinecorrection
%
% Because a lookup of a point in \METAPOST\ is a linear lookup over a linked list
% for very large paths the gain is significant when using \LUA\ because there the
% points are stored in an indexed table. The left and right points can be used
% vebose like
%
% \starttyping
% lua.mp.pathpoint(i) controls lua.mp.pathleft(i) and lua.mp.pathright(i)
% \stoptyping
%
% or more terse:
%
% \starttyping
% pointof i controls leftof i and rightof i
% \stoptyping
%
% Beware: this kind of trickery is {\em only} needed when you have very large paths
% that are to be manipulated and the. Otherwise it's overkill.
%
% \stopsection
%
% \startsection[title={Interfacing to \TEX}]
%
% The next bunch of calls is for accessing \TEX\ registers. You can set their
% values and get them as well.
%
% \starttyping
% lua.mp.getmacro(k)
% lua.mp.getdimen(k)
% lua.mp.getcount(k)
% lua.mp.gettoks (k)
%
% lua.mp.setmacro(k,v)
% lua.mp.setdimen(k,v)
% lua.mp.setcount(k,v)
% lua.mp.settoks (k,v)
% \stoptyping
%
% When you mess around with variables and run into issues it might help to
% report values on the console. The \type {report} function does this:
%
% \starttyping
% lua.mp.report(a,b)
% \stoptyping
%
% \startlinecorrection
% \startMPcode
% lua.mp.report("status","a circle") ;
% fill fullcircle xyscaled (2cm,1cm) withcolor red ;
% lua.mp.report("status","its boundingbox [@N,@N,@N,@N]",
%     xpart llcorner currentpicture, ypart llcorner currentpicture,
%     xpart urcorner currentpicture, ypart urcorner currentpicture
% ) ;
% draw boundingbox currentpicture withcolor blue ;
% report("status","the size: @Nbp x @Nbp",
%     bbwidth(currentpicture), bbheight(currentpicture)
% ) ;
% message("done") ;
% \stopMPcode
% \stoplinecorrection
%
% The console shows:
%
% \starttyping
% metapost > status : a circle
% metapost > status : its boundingbox [-28.34645,-14.17323,28.34645,14.17323]
% metapost > status : the size: 57.1929bp x 28.84647bp
% metapost > message : done
% \stoptyping
%
% There are two more getters. These can be used to access the specific graphic
% related variables set at the \TEX\ end.
%
% \starttyping
% mp.texvar(name)
% mp.texstr(name)
% \stoptyping
%
% If you have adaptive styles you might want to test for modes.
%
% \starttyping
% if lua.mp.mode("screen") : % or processingmode
%     % some action only needed for screen documents
% fi ;
% if lua.mp.systemmode("first") :
%     % some action for the first run
% fi ;
% \stoptyping
%
% For convenience these are wrapped into macros:
%
% \starttyping
% if texmode("screen") :
%     % some action only needed for screen documents
% fi ;
% if systemmode("first") :
%     % some action for the first run
% fi ;
% \stoptyping
%
% When you implement your own helpers you can fall back on some auxiliary functions
% in the \type {mp} namespace. Actually these are collected in \type {mp.aux} and
% thereby protected from being overwritten by mistake. Here they are:
%
% % mp.flush()
% % mp.size(t)
%
% \stopsection

% \startsection[title={Interfacing to \METAPOST}]
%
% There is also experimental access to some of the \METAPOST\ internals. In order
% to deal with (large) paths a few more iterator related helpers are provided too.
%
% % mp.set (numeric string path boolean)
%
% \starttyping
% n = mp.getnumeric(name)
% s = mp.getstring(name)
% b = mp.getboolean(name)
% p = mp.getpath(name)
% \stoptyping
%
% A is path a table of tables that have six values: the coordinates and the
% pre- and postcontrol. You can manipulate this table and feed it back into
% \METAPOST.
%
% \startlinecorrection
% \startMPcode
% numeric n ; n := lua.mp.newhash() ;
%
% for i=1 upto 3 :
%     lua.mp.tohash(n,i) ;
% endfor ;
%
% fill fullcircle scaled 10mm withcolor
%     if lua.mp.inhash(n,3) : green else : red fi ;
%
% fill fullcircle scaled 5mm withcolor
%     if lua.mp.inhash(n,4) : green else : red fi ;
%
% lua.mp.disposehash(n)
% \stopMPcode
% \stoplinecorrection
%
% You can also store values with keys and access them later:
%
% \startlinecorrection
% \startMPcode
% numeric n ; n := lua.mp.newhash() ;
%
% for i=1 upto 3 :
%     lua.mp.tohash(n,i,decimal sqrt(i)) ;
% endfor ;
%
% draw textext(lua.mp.fromhash(n,3))
%     ysized 1cm
%     withcolor blue ;
%
% lua.mp.disposehash(n)
% \stopMPcode
% \stoplinecorrection
%
% You can also name your own hash:
%
% \startlinecorrection
% \startMPcode
% lua.mp.newhash("foo") ;
%
% for i=1 upto 3 :
%     lua.mp.tohash("foo",i,decimal sqrt(i)) ;
% endfor ;
%
% draw textext(lua.mp.fromhash("foo",2))
%     ysized 1cm
%     withcolor green ;
%
% lua.mp.disposehash("foo")
% \stopMPcode
% \stoplinecorrection
%
% Although it might look like \METAPOST\ supports arrays the reality is that it
% doesn't really. There is a concept of suffixes but internally these are just a
% way to compose macros. The following test is one that is used in one of the
% \METAFUN\ modules written by Alan Braslau.
%
% \startlinecorrection
% \startMPcode
% path p, q[] ;
%
% if lua.mp.isarray(str q[1]) :
%     fill fullcircle scaled 1cm withcolor red ;
%     draw textext(lua.mp.prefix(str q[1])) withcolor white;
% else :
%     fill fullsquare scaled 1cm withcolor blue ;
% fi ;
%
% currentpicture := currentpicture shifted (-2cm,0) ;
%
% if lua.mp.isarray(str p) :
%     fill fullcircle scaled 1cm withcolor red ;
% else :
%     fill fullsquare scaled 1cm withcolor blue ;
% fi ;
% \stopMPcode
% \stoplinecorrection
%
% Another helper relates to extensions that \METAFUN\ adds to \METAPOST. When you
% iterate over a picture you can recognize these as objects. The next code shows
% the \LUA\ call as well as the more convenient macro call. So, \type {textext}
% clearly is a foreign object.
%
% \startlinecorrection
% \startMPcode
% picture p ; p := image (
%     fill fullcircle scaled 1cm withcolor red ;
%     draw textext("ok") withcolor white ;
% ) ;
%
% for i within p :
%     if not picture i :
%         draw i ysized 4cm ;
%     elseif isobject i :
%         draw i xsized 3cm ;
%     else :
%         draw i ysized 4cm ;
%     fi ;
% endfor ;
%
% currentpicture := currentpicture shifted (-6cm,0) ;
%
% for i within p :
%     if isobject(i) :
%         draw i xsized 5cm ;
%     else :
%         draw i ysized 3cm withcolor blue;
%     fi ;
% endfor ;
% \stopMPcode
% \stoplinecorrection

% not yet, still experimental:
%
% mp.dataset(str)
% mp.n(t)

% not for users:
%
% mp.defaultcolormodel()

% rather specialized:
%
% mp.positionpath(name)
% mp.positioncurve(name)
% mp.positionbox(name)
% mp.positionxy(name)
% mp.positionpage(name)
% mp.positionregion(name)
% mp.positionwhd(name)
% mp.positionpxy(name)
% mp.positionanchor()


% mp.cleaned
% mp.format(fmt,str)
% mp.formatted(fmt,...)
% mp.graphformat(fmt,num)

\stopsection

\stopchapter

% \startMPcode{doublefun}
%     numeric n ; n := 123.456 ;
%     lua("print('>>>>>>>>>>>> number',mp.get.number('n'))") ;
%     lua("print('>>>>>>>>>>>> number',mp.get.boolean('n'))") ;
%     lua("print('>>>>>>>>>>>> number',mp.get.string('n'))") ;
%     boolean b ; b := true ;
%     lua("print('>>>>>>>>>>>> boolean',mp.get.number('b'))") ;
%     lua("print('>>>>>>>>>>>> boolean',mp.get.boolean('b'))") ;
%     lua("print('>>>>>>>>>>>> boolean',mp.get.string('b'))") ;
%     string s ; s := "TEST" ;
%     lua("print('>>>>>>>>>>>> string',mp.get.number('s'))") ;
%     lua("print('>>>>>>>>>>>> string',mp.get.boolean('s'))") ;
%     lua("print('>>>>>>>>>>>> string',mp.get.string('s'))") ;
% \stopMPcode

% \usemodule[graph]
%
% \startluacode
%     local d = nil
%     function MP.set(data)
%         d = data
%     end
%     function MP.n()
%         mp.print(d and #d or 0)
%     end
%     function MP.get(i,j)
%         mp.print(d and d[i] and d[i][j] or 0)
%     end
% \stopluacode
%
% \startluacode
%     MP.set {
%         { 1, 0.5, 2.5 },
%         { 2, 1.0, 3.5 },
%     }
% \stopluacode
%
% \startMPpage[instance=graph,offset=2mm]
%
% draw begingraph(3cm,5cm);
%     numeric a[];
%     for j = 1 upto MP.n() :
%         path b;
%         augment.b(MP.get(j,1),MP.get(j,2));
%         augment.b(MP.get(j,1),MP.get(j,3));
%         setrange(0,0,3,4);
%         gdraw b;
%         endfor ;
% endgraph ;
% \stopMPpage

% \starttext
%
% % \enabletrackers[metapost.variables]
%
% \startMPcode
%     numeric n[]   ; for i=1 upto 10: n[i] := 1/i ; endfor ;
%     path    p[]   ; for i=1 upto 10: p[i] := fullcircle xyscaled (cm*i,cm/i) ; endfor ;
%     numeric r[][] ; for i=1 upto 4 : for j=1 upto 3 : r[i][j] := uniformdeviate(1) ; endfor ; endfor ;
%     pair    u[][] ; for i=1 step 0.5 until 4 : for j=1 step 0.1 until 2 : u[i][j] := (i,j) ; endfor ; endfor ;
%
%     passvariable("x",12345) ;
%     passarrayvariable("n-array",n,1,7,1) ;
%     passarrayvariable("p-array",p,1,7,1) ;
%     passvariable("p",(1,1) .. (2,2)) ;
%
%     startpassingvariable("b")
%         for i=1 upto 4 :
%             startpassingvariable(i)
%                 for j=1 upto 3 :
%                     passvariable(j,r[i][j])
%                 endfor
%             stoppassingvariable
%         endfor
%     stoppassingvariable ;
%
%     startpassingvariable("a")
%         startpassingvariable("test 1")
%             passvariable(1,123)
%             passvariable(2,456)
%         stoppassingvariable ;
%         startpassingvariable("test 2")
%             passvariable(0,123)
%             passvariable(1,456)
%             passvariable(2,789)
%             passvariable(999,987)
%         stoppassingvariable ;
%         startpassingvariable("test 3")
%             passvariable("first",789)
%             passvariable("second",987)
%         stoppassingvariable
%     stoppassingvariable ;
%
%     startpassingvariable("c")
%         for i=1 step 0.5 until 4 :
%             startpassingvariable(i)
%                 for j=1 step 0.1 until 2 :
%                     passvariable(j,u[i][j])
%                 endfor
%             stoppassingvariable
%         endfor
%     stoppassingvariable ;
%
%     draw fullcircle scaled 1cm ;
% \stopMPcode
%
% \ctxluacode{inspect(metapost.variables)}
%
% \ctxcommand{mprunvar("x")}

\stopcomponent