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
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
|
# YueScript Documentation
Welcome to the <b>YueScript</b> official documentation!<br/>
Here you can find the language features, usage, reference examples and resources.<br/>
Please select a chapter from the sidebar to start learning about YueScript.
# Do
When used as a statement, do works just like it does in Lua.
```yuescript
do
var = "hello"
print var
print var -- nil here
```
YueScript's **do** can also be used an expression. Allowing you to combine multiple lines into one. The result of the do expression is the last statement in its body.
```yuescript
counter = do
i = 0
->
i += 1
i
print counter!
print counter!
```
```yuescript
tbl = {
key: do
print "assigning key!"
1234
}
```
`do` expressions also support using `break` to interrupt control flow and return multiple values early:
```yuescript
status, value = do
n = 12
if n > 10
break "large", n
break "small", n
```
# Line Decorators
For convenience, the for loop and if statement can be applied to single statements at the end of the line:
```yuescript
print "hello world" if name == "Rob"
```
And with basic loops:
```yuescript
print "item: ", item for item in *items
```
And with while loops:
```yuescript
game\update! while game\isRunning!
reader\parse_line! until reader\eof!
```
# Macro
## Common Usage
Macro function is used for evaluating a string in the compile time and insert the generated codes into final compilation.
```yuescript
macro PI2 = -> math.pi * 2
area = $PI2 * 5
macro HELLO = -> "'hello world'"
print $HELLO
macro config = (debugging) ->
global debugMode = debugging == "true"
""
macro asserts = (cond) ->
debugMode and "assert #{cond}" or ""
macro assert = (cond) ->
debugMode and "assert #{cond}" or "#{cond}"
$config true
$asserts item ~= nil
$config false
value = $assert item
-- the passed expressions are treated as strings
macro and = (...) -> "#{ table.concat {...}, ' and ' }"
if $and f1!, f2!, f3!
print "OK"
```
## Insert Raw Codes
A macro function can either return a YueScript string or a config table containing Lua codes.
```yuescript
macro yueFunc = (var) -> "local #{var} = ->"
$yueFunc funcA
funcA = -> "fail to assign to the Yue macro defined variable"
macro luaFunc = (var) -> {
code: "local function #{var}() end"
type: "lua"
}
$luaFunc funcB
funcB = -> "fail to assign to the Lua macro defined variable"
macro lua = (code) -> {
:code
type: "lua"
}
-- the raw string leading and ending symbols are auto trimed
$lua[==[
-- raw Lua codes insertion
if cond then
print("output")
end
]==]
```
## Export Macro
Macro functions can be exported from a module and get imported in another module. You have to put export macro functions in a single file to be used, and only macro definition, macro importing and macro expansion in place can be put into the macro exporting module.
```yuescript
-- file: utils.yue
export macro map = (items, action) -> "[#{action} for _ in *#{items}]"
export macro filter = (items, action) -> "[_ for _ in *#{items} when #{action}]"
export macro foreach = (items, action) -> "for _ in *#{items}
#{action}"
-- file main.yue
import "utils" as {
$, -- symbol to import all macros
$foreach: $each -- rename macro $foreach to $each
}
[1, 2, 3] |> $map(_ * 2) |> $filter(_ > 4) |> $each print _
```
## Builtin Macro
There are some builtin macros but you can override them by declaring macros with the same names.
```yuescript
print $FILE -- get string of current module name
print $LINE -- get number 2
```
## Generating Macros with Macros
In YueScript, macro functions allow you to generate code at compile time. By nesting macro functions, you can create more complex generation patterns. This feature enables you to define a macro function that generates another macro function, allowing for more dynamic code generation.
```yuescript
macro Enum = (...) ->
items = {...}
itemSet = {item, true for item in *items}
(item) ->
error "got \"#{item}\", expecting one of #{table.concat items, ', '}" unless itemSet[item]
"\"#{item}\""
macro BodyType = $Enum(
Static
Dynamic
Kinematic
)
print "Valid enum type:", $BodyType Static
-- print "Compilation error with enum type:", $BodyType Unknown
```
## Argument Validation
You can declare the expected AST node types in the argument list, and check whether the incoming macro arguments meet the expectations at compile time.
```yuescript
macro printNumAndStr = (num `Num, str `String) -> |
print(
#{num}
#{str}
)
$printNumAndStr 123, "hello"
```
If you need more flexible argument checking, you can use the built-in `$is_ast` macro function to manually check at the appropriate place.
```yuescript
macro printNumAndStr = (num, str) ->
error "expected Num as first argument" unless $is_ast Num, num
error "expected String as second argument" unless $is_ast String, str
"print(#{num}, #{str})"
$printNumAndStr 123, "hello"
```
For more details about available AST nodes, please refer to the uppercased definitions in [yue_parser.cpp](https://github.com/IppClub/YueScript/blob/main/src/yuescript/yue_parser.cpp).
# Try
The syntax for Lua error handling in a common form.
```yuescript
try
func 1, 2, 3
catch err
print yue.traceback err
success, result = try
func 1, 2, 3
catch err
yue.traceback err
try func 1, 2, 3
catch err
print yue.traceback err
success, result = try func 1, 2, 3
try
print "trying"
func 1, 2, 3
-- working with if assignment pattern
if success, result := try func 1, 2, 3
catch err
print yue.traceback err
print result
```
## Try?
`try?` is a simplified use for error handling syntax that omit the boolean status from the `try` statement, and it will return the result from the try block when success, return nil instead of error object otherwise.
```yuescript
a, b, c = try? func!
-- with nil coalescing operator
a = (try? func!) ?? "default"
-- as function argument
f try? func!
-- with catch block
f try?
print 123
func!
catch e
print e
e
```
# Table Literals
Like in Lua, tables are delimited in curly braces.
```yuescript
some_values = {1, 2, 3, 4}
```
Unlike Lua, assigning a value to a key in a table is done with **:** (instead of **=**).
```yuescript
some_values = {
name: "Bill",
age: 200,
["favorite food"]: "rice"
}
```
The curly braces can be left off if a single table of key value pairs is being assigned.
```yuescript
profile =
height: "4 feet",
shoe_size: 13,
favorite_foods: ["ice cream", "donuts"]
```
Newlines can be used to delimit values instead of a comma (or both):
```yuescript
values = {
1, 2, 3, 4
5, 6, 7, 8
name: "superman"
occupation: "crime fighting"
}
```
When creating a single line table literal, the curly braces can also be left off:
```yuescript
my_function dance: "Tango", partner: "none"
y = type: "dog", legs: 4, tails: 1
```
The keys of a table literal can be language keywords without being escaped:
```yuescript
tbl = {
do: "something"
end: "hunger"
}
```
If you are constructing a table out of variables and wish the keys to be the same as the variable names, then the **:** prefix operator can be used:
```yuescript
hair = "golden"
height = 200
person = { :hair, :height, shoe_size: 40 }
print_table :hair, :height
```
If you want the key of a field in the table to to be result of an expression, then you can wrap it in **[ ]**, just like in Lua. You can also use a string literal directly as a key, leaving out the square brackets. This is useful if your key has any special characters.
```yuescript
t = {
[1 + 2]: "hello"
"hello world": true
}
```
Lua tables have both an array part and a hash part, but sometimes it's useful to make a semantic distinction between the two. You can use **[ ]** instead of **{ }** to explicitly declare a table as an array, doing so will prevent any key-value pairs from being written inside it.
```yuescript
some_values = [1, 2, 3, 4]
list_with_one_element = [1, ]
```
# Comprehensions
Comprehensions provide a convenient syntax for constructing a new table by iterating over some existing object and applying an expression to its values. There are two kinds of comprehensions: list comprehensions and table comprehensions. They both produce Lua tables; list comprehensions accumulate values into an array-like table, and table comprehensions let you set both the key and the value on each iteration.
## List Comprehensions
The following creates a copy of the items table but with all the values doubled.
```yuescript
items = [ 1, 2, 3, 4 ]
doubled = [item * 2 for i, item in ipairs items]
```
The items included in the new table can be restricted with a when clause:
```yuescript
slice = [item for i, item in ipairs items when i > 1 and i < 3]
```
Because it is common to iterate over the values of a numerically indexed table, an **\*** operator is introduced. The doubled example can be rewritten as:
```yuescript
doubled = [item * 2 for item in *items]
```
In list comprehensions, you can also use the spread operator `...` to flatten nested lists, achieving a flat map effect:
```yuescript
data =
a: [1, 2, 3]
b: [4, 5, 6]
flat = [...v for k,v in pairs data]
-- flat is now [1, 2, 3, 4, 5, 6]
```
The for and when clauses can be chained as much as desired. The only requirement is that a comprehension has at least one for clause.
Using multiple for clauses is the same as using nested loops:
```yuescript
x_coords = [4, 5, 6, 7]
y_coords = [9, 2, 3]
points = [ [x, y] for x in *x_coords \
for y in *y_coords]
```
Numeric for loops can also be used in comprehensions:
```yuescript
evens = [i for i = 1, 100 when i % 2 == 0]
```
## Table Comprehensions
The syntax for table comprehensions is very similar, only differing by using **{** and **}** and taking two values from each iteration.
This example makes a copy of the tablething:
```yuescript
thing = {
color: "red"
name: "fast"
width: 123
}
thing_copy = {k, v for k, v in pairs thing}
```
```yuescript
no_color = {k, v for k, v in pairs thing when k != "color"}
```
The **\*** operator is also supported. Here we create a square root look up table for a few numbers.
```yuescript
numbers = [1, 2, 3, 4]
sqrts = {i, math.sqrt i for i in *numbers}
```
The key-value tuple in a table comprehension can also come from a single expression, in which case the expression should return two values. The first is used as the key and the second is used as the value:
In this example we convert an array of pairs to a table where the first item in the pair is the key and the second is the value.
```yuescript
tuples = [ ["hello", "world"], ["foo", "bar"]]
tbl = {unpack tuple for tuple in *tuples}
```
## Slicing
A special syntax is provided to restrict the items that are iterated over when using the **\*** operator. This is equivalent to setting the iteration bounds and a step size in a for loop.
Here we can set the minimum and maximum bounds, taking all items with indexes between 1 and 5 inclusive:
```yuescript
slice = [item for item in *items[1, 5]]
```
Any of the slice arguments can be left off to use a sensible default. In this example, if the max index is left off it defaults to the length of the table. This will take everything but the first element:
```yuescript
slice = [item for item in *items[2,]]
```
If the minimum bound is left out, it defaults to 1. Here we only provide a step size and leave the other bounds blank. This takes all odd indexed items: (1, 3, 5, …)
```yuescript
slice = [item for item in *items[,,2]]
```
Both the minimum and maximum bounds can be negative, which means that the bounds are counted from the end of the table.
```yuescript
-- take the last 4 items
slice = [item for item in *items[-4,-1]]
```
The step size can also be negative, which means that the items are taken in reverse order.
```yuescript
reverse_slice = [item for item in *items[-1,1,-1]]
```
### Slicing Expression
Slicing can also be used as an expression. This is useful for getting a sub-list of a table.
```yuescript
-- take the 2nd and 4th items as a new list
sub_list = items[2, 4]
-- take the last 4 items
last_four_items = items[-4, -1]
```
# Object Oriented Programming
In these examples, the generated Lua code may appear overwhelming. It is best to focus on the meaning of the YueScript code at first, then look into the Lua code if you wish to know the implementation details.
A simple class:
```yuescript
class Inventory
new: =>
@items = {}
add_item: (name) =>
if @items[name]
@items[name] += 1
else
@items[name] = 1
```
A class is declared with a class statement followed by a table-like declaration where all of the methods and properties are listed.
The new property is special in that it will become the constructor.
Notice how all the methods in the class use the fat arrow function syntax. When calling methods on a instance, the instance itself is sent in as the first argument. The fat arrow handles the creation of a self argument.
The @ prefix on a variable name is shorthand for self.. @items becomes self.items.
The class block also supports metatable fields by writing metamethod keys in angle brackets, such as `<tostring>`.
```yuescript
class User
new: (@name) =>
<tostring>: => "User(#{@name})"
print tostring User "Yue"
```
Creating an instance of the class is done by calling the name of the class as a function.
```yuescript
inv = Inventory!
inv\add_item "t-shirt"
inv\add_item "pants"
```
Because the instance of the class needs to be sent to the methods when they are called, the \ operator is used.
All properties of a class are shared among the instances. This is fine for functions, but for other types of objects, undesired results may occur.
Consider the example below, the clothes property is shared amongst all instances, so modifications to it in one instance will show up in another:
```yuescript
class Person
clothes: []
give_item: (name) =>
table.insert @clothes, name
a = Person!
b = Person!
a\give_item "pants"
b\give_item "shirt"
-- will print both pants and shirt
print item for item in *a.clothes
```
The proper way to avoid this problem is to create the mutable state of the object in the constructor:
```yuescript
class Person
new: =>
@clothes = []
```
## Inheritance
The extends keyword can be used in a class declaration to inherit the properties and methods from another class.
```yuescript
class BackPack extends Inventory
size: 10
add_item: (name) =>
if #@items > size then error "backpack is full"
super name
```
Here we extend our Inventory class, and limit the amount of items it can carry.
In this example, we don't define a constructor on the subclass, so the parent class' constructor is called when we make a new instance. If we did define a constructor then we can use the super method to call the parent constructor.
Whenever a class inherits from another, it sends a message to the parent class by calling the method \_\_inherited on the parent class if it exists. The function receives two arguments, the class that is being inherited and the child class.
```yuescript
class Shelf
@__inherited: (child) =>
print @__name, "was inherited by", child.__name
-- will print: Shelf was inherited by Cupboard
class Cupboard extends Shelf
```
## Super
**super** is a special keyword that can be used in two different ways: It can be treated as an object, or it can be called like a function. It only has special functionality when inside a class.
When called as a function, it will call the function of the same name in the parent class. The current self will automatically be passed as the first argument. (As seen in the inheritance example above)
When super is used as a normal value, it is a reference to the parent class object.
It can be accessed like any of object in order to retrieve values in the parent class that might have been shadowed by the child class.
When the \ calling operator is used with super, self is inserted as the first argument instead of the value of super itself. When using . to retrieve a function, the raw function is returned.
A few examples of using super in different ways:
```yuescript
class MyClass extends ParentClass
a_method: =>
-- the following have the same effect:
super "hello", "world"
super\a_method "hello", "world"
super.a_method self, "hello", "world"
-- super as a value is equal to the parent class:
assert super == ParentClass
```
**super** can also be used on left side of a Function Stub. The only major difference is that instead of the resulting function being bound to the value of super, it is bound to self.
## Types
Every instance of a class carries its type with it. This is stored in the special \_\_class property. This property holds the class object. The class object is what we call to build a new instance. We can also index the class object to retrieve class methods and properties.
```yuescript
b = BackPack!
assert b.__class == BackPack
print BackPack.size -- prints 10
```
## Class Objects
The class object is what we create when we use a class statement. The class object is stored in a variable of the same name of the class.
The class object can be called like a function in order to create new instances. That's how we created instances of classes in the examples above.
A class is made up of two tables. The class table itself, and the base table. The base is used as the metatable for all the instances. All properties listed in the class declaration are placed in the base.
The class object's metatable reads properties from the base if they don't exist in the class object. This means we can access functions and properties directly from the class.
It is important to note that assigning to the class object does not assign into the base, so it's not a valid way to add new methods to instances. Instead the base must explicitly be changed. See the \_\_base field below.
The class object has a couple special properties:
The name of the class as when it was declared is stored as a string in the \_\_name field of the class object.
```yuescript
print BackPack.__name -- prints Backpack
```
The base object is stored in \_\_base. We can modify this table to add functionality to instances that have already been created and ones that are yet to be created.
If the class extends from anything, the parent class object is stored in \_\_parent.
## Class Variables
We can create variables directly in the class object instead of in the base by using @ in the front of the property name in a class declaration.
```yuescript
class Things
@some_func: => print "Hello from", @__name
Things\some_func!
-- class variables not visible in instances
assert Things().some_func == nil
```
In expressions, we can use @@ to access a value that is stored in the **class of self. Thus, @@hello is shorthand for self.**class.hello.
```yuescript
class Counter
@count: 0
new: =>
@@count += 1
Counter!
Counter!
print Counter.count -- prints 2
```
The calling semantics of @@ are similar to @. Calling a @@ name will pass the class in as the first argument using Lua's colon syntax.
```yuescript
@@hello 1,2,3,4
```
## Class Declaration Statements
In the body of a class declaration, we can have normal expressions in addition to key/value pairs. In this context, self is equal to the class object.
Here is an alternative way to create a class variable compared to what's described above:
```yuescript
class Things
@class_var = "hello world"
```
These expressions are executed after all the properties have been added to the base.
All variables declared in the body of the class are local to the classes properties. This is convenient for placing private values or helper functions that only the class methods can access:
```yuescript
class MoreThings
secret = 123
log = (msg) -> print "LOG:", msg
some_method: =>
log "hello world: " .. secret
```
## @ and @@ Values
When @ and @@ are prefixed in front of a name they represent, respectively, that name accessed in self and self.\_\_class.
If they are used all by themselves, they are aliases for self and self.\_\_class.
```yuescript
assert @ == self
assert @@ == self.__class
```
For example, a quick way to create a new instance of the same class from an instance method using @@:
```yuescript
some_instance_method = (...) => @@ ...
```
## Constructor Property Promotion
To reduce the boilerplate code for definition of simple value objects. You can write a simple class like:
```yuescript
class Something
new: (@foo, @bar, @@biz, @@baz) =>
-- Which is short for
class Something
new: (foo, bar, biz, baz) =>
@foo = foo
@bar = bar
@@biz = biz
@@baz = baz
```
You can also use this syntax for a common function to initialize a object's fields.
```yuescript
new = (@fieldA, @fieldB) => @
obj = new {}, 123, "abc"
print obj
```
## Class Expressions
The class syntax can also be used as an expression which can be assigned to a variable or explicitly returned.
```yuescript
x = class Bucket
drops: 0
add_drop: => @drops += 1
```
## Anonymous classes
The name can be left out when declaring a class. The \_\_name attribute will be nil, unless the class expression is in an assignment. The name on the left hand side of the assignment is used instead of nil.
```yuescript
BigBucket = class extends Bucket
add_drop: => @drops += 10
assert Bucket.__name == "BigBucket"
```
You can even leave off the body, meaning you can write a blank anonymous class like this:
```yuescript
x = class
```
## Class Mixing
You can do mixing with keyword `using` to copy functions from either a plain table or a predefined class object into your new class. When doing mixing with a plain table, you can override the class indexing function (metamethod `__index`) to your customized implementation. When doing mixing with an existing class object, the class object's metamethods won't be copied.
```yuescript
MyIndex = __index: var: 1
class X using MyIndex
func: =>
print 123
x = X!
print x.var
class Y using X
y = Y!
y\func!
assert y.__class.__parent ~= X -- X is not parent of Y
```
# With Statement
A common pattern involving the creation of an object is calling a series of functions and setting a series of properties immediately after creating it.
This results in repeating the name of the object multiple times in code, adding unnecessary noise. A common solution to this is to pass a table in as an argument which contains a collection of keys and values to overwrite. The downside to this is that the constructor of this object must support this form.
The with block helps to alleviate this. Within a with block we can use a special statements that begin with either . or \ which represent those operations applied to the object we are using with on.
For example, we work with a newly created object:
```yuescript
with Person!
.name = "Oswald"
\add_relative my_dad
\save!
print .name
```
The with statement can also be used as an expression which returns the value it has been giving access to.
```yuescript
file = with File "favorite_foods.txt"
\set_encoding "utf8"
```
`with` expressions support `break` with one value:
```yuescript
result = with obj
break .value
```
After `break value` is used inside `with`, the `with` expression no longer returns its target object. Instead, it returns the value from `break`.
```yuescript
a = with obj
.x = 1
-- a is obj
b = with obj
break .x
-- b is .x, not obj
```
Unlike `for` / `while` / `repeat` / `do`, `with` only supports one break value.
Or…
```yuescript
create_person = (name, relatives) ->
with Person!
.name = name
\add_relative relative for relative in *relatives
me = create_person "Leaf", [dad, mother, sister]
```
In this usage, with can be seen as a special form of the K combinator.
The expression in the with statement can also be an assignment, if you want to give a name to the expression.
```yuescript
with str := "Hello"
print "original:", str
print "upper:", \upper!
```
You can access special keys with `[]` in a `with` statement.
```yuescript
with tb
[1] = 1
print [2]
with [abc]
[3] = [2]\func!
["key-name"] = value
[] = "abc" -- appending to "tb"
```
`with?` is an enhanced version of `with` syntax, which introduces an existential check to safely access objects that may be nil without explicit null checks.
```yuescript
with? obj
print .name
```
# Assignment
The variable is dynamic typed and is defined as local by default. But you can change the scope of declaration by **local** and **global** statement.
```yuescript
hello = "world"
a, b, c = 1, 2, 3
hello = 123 -- uses the existing variable
```
## Perform Update
You can perform update assignment with many binary operators.
```yuescript
x = 1
x += 1
x -= 1
x *= 10
x /= 10
x %= 10
s ..= "world" -- will add a new local if local variable is not exist
arg or= "default value"
```
## Chaining Assignment
You can do chaining assignment to assign multiple items to hold the same value.
```yuescript
a = b = c = d = e = 0
x = y = z = f!
```
## Explicit Locals
```yuescript
do
local a = 1
local *
print "forward declare all variables as locals"
x = -> 1 + y + z
y, z = 2, 3
global instance = Item\new!
do
local X = 1
local ^
print "only forward declare upper case variables"
a = 1
B = 2
```
## Explicit Globals
```yuescript
do
global a = 1
global *
print "declare all variables as globals"
x = -> 1 + y + z
y, z = 2, 3
do
global X = 1
global ^
print "only declare upper case variables as globals"
a = 1
B = 2
local Temp = "a local value"
```
# Varargs Assignment
You can assign the results returned from a function to a varargs symbol `...`. And then access its content using the Lua way.
```yuescript
list = [1, 2, 3, 4, 5]
fn = (ok) -> ok, table.unpack list
ok, ... = fn true
count = select '#', ...
first = select 1, ...
print ok, count, first
```
# If Assignment
`if` and `elseif` blocks can take an assignment in place of a conditional expression. Upon evaluating the conditional, the assignment will take place and the value that was assigned to will be used as the conditional expression. The assigned variable is only in scope for the body of the conditional, meaning it is never available if the value is not truthy. And you have to use "the walrus operator" `:=` instead of `=` to do assignment.
```yuescript
if user := database.find_user "moon"
print user.name
```
```yuescript
if hello := os.getenv "hello"
print "You have hello", hello
elseif world := os.getenv "world"
print "you have world", world
else
print "nothing :("
```
If assignment with multiple return values. Only the first value is getting checked, other values are scoped.
```yuescript
if success, result := pcall -> "get result without problems"
print result -- variable result is scoped
print "OK"
```
## While Assignment
You can also use if assignment in a while loop to get the value as the loop condition.
```yuescript
while byte := stream\read_one!
-- do something with the byte
print byte
```
# Destructuring Assignment
Destructuring assignment is a way to quickly extract values from a table by their name or position in array based tables.
Typically when you see a table literal, {1,2,3}, it is on the right hand side of an assignment because it is a value. Destructuring assignment swaps the role of the table literal, and puts it on the left hand side of an assign statement.
This is best explained with examples. Here is how you would unpack the first two values from a table:
```yuescript
thing = [1, 2]
[a, b] = thing
print a, b
```
In the destructuring table literal, the key represents the key to read from the right hand side, and the value represents the name the read value will be assigned to.
```yuescript
obj = {
hello: "world"
day: "tuesday"
length: 20
}
{hello: hello, day: the_day} = obj
print hello, the_day
:day = obj -- OK to do simple destructuring without braces
```
This also works with nested data structures as well:
```yuescript
obj2 = {
numbers: [1, 2, 3, 4]
properties: {
color: "green"
height: 13.5
}
}
{numbers: [first, second], properties: {color: color}} = obj2
print first, second, color
```
If the destructuring statement is complicated, feel free to spread it out over a few lines. A slightly more complicated example:
```yuescript
{
numbers: [first, second]
properties: {
color: color
}
} = obj2
```
It's common to extract values from at table and assign them the local variables that have the same name as the key. In order to avoid repetition we can use the **:** prefix operator:
```yuescript
{:concat, :insert} = table
```
This is effectively the same as import, but we can rename fields we want to extract by mixing the syntax:
```yuescript
{:mix, :max, random: rand} = math
```
You can write default values while doing destructuring like:
```yuescript
{:name = "nameless", :job = "jobless"} = person
```
You can use `_` as placeholder when doing a list destructuring:
```yuescript
[_, two, _, four] = items
```
## Range Destructuring
You can use the spread operator `...` in list destructuring to capture a range of values. This is useful when you want to extract specific elements from the beginning and end of a list while collecting the rest in between.
```yuescript
orders = ["first", "second", "third", "fourth", "last"]
[first, ...bulk, last] = orders
print first -- prints: first
print bulk -- prints: {"second", "third", "fourth"}
print last -- prints: last
```
The spread operator can be used in different positions to capture different ranges, and you can use `_` as a placeholder for the values you don't want to capture:
```yuescript
-- Capture everything after first element
[first, ...rest] = orders
-- Capture everything before last element
[...start, last] = orders
-- Capture things except the middle elements
[first, ..._, last] = orders
```
## Destructuring In Other Places
Destructuring can also show up in places where an assignment implicitly takes place. An example of this is a for loop:
```yuescript
tuples = [
["hello", "world"]
["egg", "head"]
]
for [left, right] in *tuples
print left, right
```
We know each element in the array table is a two item tuple, so we can unpack it directly in the names clause of the for statement using a destructure.
# The Using Clause; Controlling Destructive Assignment
While lexical scoping can be a great help in reducing the complexity of the code we write, things can get unwieldy as the code size increases. Consider the following snippet:
```yuescript
i = 100
-- many lines of code...
my_func = ->
i = 10
while i > 0
print i
i -= 1
my_func!
print i -- will print 0
```
In my_func, we've overwritten the value of i mistakenly. In this example it is quite obvious, but consider a large, or foreign code base where it isn't clear what names have already been declared.
It would be helpful to say which variables from the enclosing scope we intend on change, in order to prevent us from changing others by accident.
The using keyword lets us do that. using nil makes sure that no closed variables are overwritten in assignment. The using clause is placed after the argument list in a function, or in place of it if there are no arguments.
```yuescript
i = 100
my_func = (using nil) ->
i = "hello" -- a new local variable is created here
my_func!
print i -- prints 100, i is unaffected
```
Multiple names can be separated by commas. Closure values can still be accessed, they just cant be modified:
```yuescript
tmp = 1213
i, k = 100, 50
my_func = (add using k, i) ->
tmp = tmp + add -- a new local tmp is created
i += tmp
k += tmp
my_func(22)
print i, k -- these have been updated
```
# Usage
## Lua Module
Use YueScript module in Lua:
- **Case 1**
Require "your_yuescript_entry.yue" in Lua.
```lua
require("yue")("your_yuescript_entry")
```
And this code still works when you compile "your_yuescript_entry.yue" to "your_yuescript_entry.lua" in the same path. In the rest YueScript files just use the normal **require** or **import**. The code line numbers in error messages will also be handled correctly.
- **Case 2**
Require YueScript module and rewite message by hand.
```lua
local yue = require("yue")
yue.insert_loader()
local success, result = xpcall(function()
return require("yuescript_module_name")
end, function(err)
return yue.traceback(err)
end)
```
- **Case 3**
Use the YueScript compiler function in Lua.
```lua
local yue = require("yue")
local codes, err, globals = yue.to_lua([[
f = ->
print "hello world"
f!
]],{
implicit_return_root = true,
reserve_line_number = true,
lint_global = true,
space_over_tab = false,
options = {
target = "5.4",
path = "/script"
}
})
```
## YueScript Tool
Use YueScript tool with:
```shell
> yue -h
Usage: yue
[options] [<file/directory>] ...
yue -e <code_or_file> [args...]
yue -w [<directory>] [options]
yue -
Notes:
- '-' / '--' must be the first and only argument.
- '-o/--output' can not be used with multiple input files.
- '-w/--watch' can not be used with file input (directory only).
- with '-e/--execute', remaining tokens are treated as script args.
Options:
-h, --help Show this help message and exit.
-e <str>, --execute <str> Execute a file or raw codes
-m, --minify Generate minified codes
-r, --rewrite Rewrite output to match original line numbers
-t <output_to>, --output-to <output_to>
Specify where to place compiled files
-o <file>, --output <file> Write output to file
-p, --print Write output to standard out
-b, --benchmark Dump compile time (doesn't write output)
-g, --globals Dump global variables used in NAME LINE COLUMN
-s, --spaces Use spaces in generated codes instead of tabs
-l, --line-numbers Write line numbers from source codes
-j, --no-implicit-return Disable implicit return at end of file
-c, --reserve-comments Reserve comments before statement from source codes
-w [<dir>], --watch [<dir>]
Watch changes and compile every file under directory
-v, --version Print version
- Read from standard in, print to standard out
(Must be first and only argument)
-- Same as '-' (kept for backward compatibility)
--target <version> Specify the Lua version that codes will be generated to
(version can only be 5.1 to 5.5)
--path <path_str> Append an extra Lua search path string to package.path
--<key>=<value> Pass compiler option in key=value form (existing behavior)
Execute without options to enter REPL, type symbol '$'
in a single line to start/stop multi-line mode
```
Use cases:
Recursively compile every YueScript file with extension **.yue** under current path: **yue .**
Compile and save results to a target path: **yue -t /target/path/ .**
Compile and reserve debug info: **yue -l .**
Compile and generate minified codes: **yue -m .**
Execute raw codes: **yue -e 'print 123'**
Execute a YueScript file: **yue -e main.yue**
# Introduction
YueScript is a dynamic language that compiles to Lua. And it's a [MoonScript](https://github.com/leafo/moonscript) dialect. The codes written in YueScript are expressive and extremely concise. And it is suitable for writing some changing application logic with more maintainable codes and runs in a Lua embeded environment such as games or website servers.
Yue (月) is the name of moon in Chinese and it's pronounced as [jyɛ].
## An Overview of YueScript
```yuescript
-- import syntax
import p, to_lua from "yue"
-- object literals
inventory =
equipment:
- "sword"
- "shield"
items:
- name: "potion"
count: 10
- name: "bread"
count: 3
-- list comprehension
map = (arr, action) ->
[action item for item in *arr]
filter = (arr, cond) ->
[item for item in *arr when cond item]
reduce = (arr, init, action): init ->
init = action init, item for item in *arr
-- pipe operator
[1, 2, 3]
|> map (x) -> x * 2
|> filter (x) -> x > 4
|> reduce 0, (a, b) -> a + b
|> print
-- metatable manipulation
apple =
size: 15
<index>:
color: 0x00ffff
with apple
p .size, .color, .<index> if .<>?
-- js-like export syntax
export 🌛 = "Script of Moon"
```
## About Dora SSR
YueScript is being developed and maintained alongside the open-source game engine [Dora SSR](https://github.com/Dora-SSR/Dora-SSR). It has been used to create engine tools, game demos and prototypes, validating its capabilities in real-world scenarios while enhancing the Dora SSR development experience.
# Installation
## Lua Module
Install [luarocks](https://luarocks.org), a package manager for Lua modules. Then install it as a Lua module and executable with:
```shell
luarocks install yuescript
```
Or you can build `yue.so` file with:
```shell
make shared LUAI=/usr/local/include/lua LUAL=/usr/local/lib/lua
```
Then get the binary file from path **bin/shared/yue.so**.
## Build Binary Tool
Clone this repo, then build and install executable with:
```shell
make install
```
Build YueScript tool without macro feature:
```shell
make install NO_MACRO=true
```
Build YueScript tool without built-in Lua binary:
```shell
make install NO_LUA=true
```
## Download Precompiled Binary
You can download precompiled binary files, including binary executable files compatible with different Lua versions and library files.
Download precompiled binary files from [here](https://github.com/IppClub/YueScript/releases).
# Conditionals
```yuescript
have_coins = false
if have_coins
print "Got coins"
else
print "No coins"
```
A short syntax for single statements can also be used:
```yuescript
have_coins = false
if have_coins then print "Got coins" else print "No coins"
```
Because if statements can be used as expressions, this can also be written as:
```yuescript
have_coins = false
print if have_coins then "Got coins" else "No coins"
```
Conditionals can also be used in return statements and assignments:
```yuescript
is_tall = (name) ->
if name == "Rob"
true
else
false
message = if is_tall "Rob"
"I am very tall"
else
"I am not so tall"
print message -- prints: I am very tall
```
The opposite of if is unless:
```yuescript
unless os.date("%A") == "Monday"
print "it is not Monday!"
```
```yuescript
print "You're lucky!" unless math.random! > 0.1
```
## In Expression
You can write range checking code with an `in-expression`.
```yuescript
a = 5
if a in [1, 3, 5, 7]
print "checking equality with discrete values"
if a in list
print "checking if `a` is in a list"
```
The `in` operator can also be used with tables and supports the `not in` variant for negation:
```yuescript
has = "foo" in {"bar", "foo"}
if a in {1, 2, 3}
print "a is in the table"
not_exist = item not in list
check = -> value not in table
```
A single-element list or table checks for equality with that element:
```yuescript
-- [1,] checks if value == 1
c = a in [1,]
-- {1} also checks if value == 1
c = a in {1}
-- Without comma, [1] is indexing (tb[1])
with tb
c = a in [1]
```
# For Loop
There are two for loop forms, just like in Lua. A numeric one and a generic one:
```yuescript
for i = 10, 20
print i
for k = 1, 15, 2 -- an optional step provided
print k
for key, value in pairs object
print key, value
```
The slicing and **\*** operators can be used, just like with comprehensions:
```yuescript
for item in *items[2, 4]
print item
```
A shorter syntax is also available for all variations when the body is only a single line:
```yuescript
for item in *items do print item
for j = 1, 10, 3 do print j
```
A for loop can also be used as an expression. The last statement in the body of the for loop is coerced into an expression and appended to an accumulating array table.
Doubling every even number:
```yuescript
doubled_evens = for i = 1, 20
if i % 2 == 0
i * 2
else
i
```
In addition, for loops support break with return values, allowing the loop itself to be used as an expression that exits early with meaningful results.
For example, to find the first number greater than 10:
```yuescript
first_large = for n in *numbers
break n if n > 10
```
This break-with-value syntax enables concise and expressive search or early-exit patterns directly within loop expressions.
For loop expressions can break with multiple values:
```yuescript
key, score = for k, v in pairs data
break k, v * 10 if k == "target"
```
You can also filter values by combining the for loop expression with the continue statement.
For loops at the end of a function body are not accumulated into a table for a return value (Instead the function will return nil). Either an explicit return statement can be used, or the loop can be converted into a list comprehension.
```yuescript
func_a = -> for i = 1, 10 do print i
func_b = -> return for i = 1, 10 do i
print func_a! -- prints nil
print func_b! -- prints table object
```
This is done to avoid the needless creation of tables for functions that don't need to return the results of the loop.
# Continue
A continue statement can be used to skip the current iteration in a loop.
```yuescript
i = 0
while i < 10
i += 1
continue if i % 2 == 0
print i
```
continue can also be used with loop expressions to prevent that iteration from accumulating into the result. This examples filters the array table into just even numbers:
```yuescript
my_numbers = [1, 2, 3, 4, 5, 6]
odds = for x in *my_numbers
continue if x % 2 == 1
x
```
# Switch
The switch statement is shorthand for writing a series of if statements that check against the same value. Note that the value is only evaluated once. Like if statements, switches can have an else block to handle no matches. Comparison is done with the == operator. In switch statement, you can also use assignment expression to store temporary variable value.
```yuescript
switch name := "Dan"
when "Robert"
print "You are Robert"
when "Dan", "Daniel"
print "Your name, it's Dan"
else
print "I don't know about you with name #{name}"
```
A switch when clause can match against multiple values by listing them out comma separated.
Switches can be used as expressions as well, here we can assign the result of the switch to a variable:
```yuescript
b = 1
next_number = switch b
when 1
2
when 2
3
else
error "can't count that high!"
```
We can use the then keyword to write a switch's when block on a single line. No extra keyword is needed to write the else block on a single line.
```yuescript
msg = switch math.random(1, 5)
when 1 then "you are lucky"
when 2 then "you are almost lucky"
else "not so lucky"
```
If you want to write code with one less indent when writing a switch statement, you can put the first when clause on the statement start line, and then all other clauses can be written with one less indent.
```yuescript
switch math.random(1, 5)
when 1
print "you are lucky" -- two indents
else
print "not so lucky"
switch math.random(1, 5) when 1
print "you are lucky" -- one indent
else
print "not so lucky"
```
It is worth noting the order of the case comparison expression. The case's expression is on the left hand side. This can be useful if the case's expression wants to overwrite how the comparison is done by defining an eq metamethod.
## Table Matching
You can do table matching in a switch when clause, if the table can be destructured by a specific structure and get non-nil values.
```yuescript
items =
* x: 100
y: 200
* width: 300
height: 400
for item in *items
switch item
when :x, :y
print "Vec2 #{x}, #{y}"
when :width, :height
print "size #{width}, #{height}"
```
You can use default values to optionally destructure the table for some fields.
```yuescript
item = {}
{pos: {:x = 50, :y = 200}} = item -- get error: attempt to index a nil value (field 'pos')
switch item
when {pos: {:x = 50, :y = 200}}
print "Vec2 #{x}, #{y}" -- table destructuring will still pass
```
You can also match against array elements, table fields, and even nested structures with array or table literals.
Match against array elements.
```yuescript
switch tb
when [1, 2, 3]
print "1, 2, 3"
when [1, b, 3]
print "1, #{b}, 3"
when [1, 2, b = 3] -- b has a default value
print "1, 2, #{b}"
```
Match against table fields with destructuring.
```yuescript
switch tb
when success: true, :result
print "success", result
when success: false
print "failed", result
else
print "invalid"
```
Match against nested table structures.
```yuescript
switch tb
when data: {type: "success", :content}
print "success", content
when data: {type: "error", :content}
print "failed", content
else
print "invalid"
```
Match against array of tables.
```yuescript
switch tb
when [
{a: 1, b: 2}
{a: 3, b: 4}
{a: 5, b: 6}
fourth
]
print "matched", fourth
```
Match against a list and capture a range of elements.
```yuescript
segments = ["admin", "users", "logs", "view"]
switch segments
when [...groups, resource, action]
print "Group:", groups -- prints: {"admin", "users"}
print "Resource:", resource -- prints: "logs"
print "Action:", action -- prints: "view"
```
# While Loop
The while loop also comes in four variations:
```yuescript
i = 10
while i > 0
print i
i -= 1
while running == true do my_function!
```
```yuescript
i = 10
until i == 0
print i
i -= 1
until running == false do my_function!
```
Like for loops, the while loop can also be used as an expression. While and until loop expressions support `break` with multiple return values.
```yuescript
value, doubled = while true
n = get_next!
break n, n * 2 if n > 10
```
Additionally, for a function to return the accumulated value of a while loop, the statement must be explicitly returned.
## Repeat Loop
The repeat loop comes from Lua:
```yuescript
i = 10
repeat
print i
i -= 1
until i == 0
```
Repeat loop expressions also support `break` with multiple return values:
```yuescript
i = 1
value, scaled = repeat
break i, i * 100 if i > 3
i += 1
until false
```
# Function Stubs
It is common to pass a function from an object around as a value, for example, passing an instance method into a function as a callback. If the function expects the object it is operating on as the first argument then you must somehow bundle that object with the function so it can be called properly.
The function stub syntax is a shorthand for creating a new closure function that bundles both the object and function. This new function calls the wrapped function in the correct context of the object.
Its syntax is the same as calling an instance method with the \ operator but with no argument list provided.
```yuescript
my_object = {
value: 1000
write: => print "the value:", @value
}
run_callback = (func) ->
print "running callback..."
func!
-- this will not work:
-- the function has to no reference to my_object
run_callback my_object.write
-- function stub syntax
-- lets us bundle the object into a new function
run_callback my_object\write
```
# Backcalls
Backcalls are used for unnesting callbacks. They are defined using arrows pointed to the left as the last parameter by default filling in a function call. All the syntax is mostly the same as regular arrow functions except that it is just pointing the other way and the function body does not require indent.
```yuescript
x <- f
print "hello" .. x
```
Fat arrow functions are also available.
```yuescript
<= f
print @value
```
You can specify a placeholder for where you want the backcall function to go as a parameter.
```yuescript
(x) <- map _, [1, 2, 3]
x * 2
```
If you wish to have further code after your backcalls, you can set them aside with a do statement. And the parentheses can be omitted with non-fat arrow functions.
```yuescript
result, msg = do
data <- readAsync "filename.txt"
print data
info <- processAsync data
check info
print result, msg
```
# Function Literals
All functions are created using a function expression. A simple function is denoted using the arrow: **->**.
```yuescript
my_function = ->
my_function() -- call the empty function
```
The body of the function can either be one statement placed directly after the arrow, or it can be a series of statements indented on the following lines:
```yuescript
func_a = -> print "hello world"
func_b = ->
value = 100
print "The value:", value
```
If a function has no arguments, it can be called using the ! operator, instead of empty parentheses. The ! invocation is the preferred way to call functions with no arguments.
```yuescript
func_a!
func_b()
```
Functions with arguments can be created by preceding the arrow with a list of argument names in parentheses:
```yuescript
sum = (x, y) -> print "sum", x + y
```
Functions can be called by listing the arguments after the name of an expression that evaluates to a function. When chaining together function calls, the arguments are applied to the closest function to the left.
```yuescript
sum 10, 20
print sum 10, 20
a b c "a", "b", "c"
```
In order to avoid ambiguity in when calling functions, parentheses can also be used to surround the arguments. This is required here in order to make sure the right arguments get sent to the right functions.
```yuescript
print "x:", sum(10, 20), "y:", sum(30, 40)
```
There must not be any space between the opening parenthesis and the function.
Functions will coerce the last statement in their body into a return statement, this is called implicit return:
```yuescript
sum = (x, y) -> x + y
print "The sum is ", sum 10, 20
```
And if you need to explicitly return, you can use the return keyword:
```yuescript
sum = (x, y) -> return x + y
```
Just like in Lua, functions can return multiple values. The last statement must be a list of values separated by commas:
```yuescript
mystery = (x, y) -> x + y, x - y
a, b = mystery 10, 20
```
## Fat Arrows
Because it is an idiom in Lua to send an object as the first argument when calling a method, a special syntax is provided for creating functions which automatically includes a self argument.
```yuescript
func = (num) => @value + num
```
## Argument Defaults
It is possible to provide default values for the arguments of a function. An argument is determined to be empty if its value is nil. Any nil arguments that have a default value will be replace before the body of the function is run.
```yuescript
my_function = (name = "something", height = 100) ->
print "Hello I am", name
print "My height is", height
```
An argument default value expression is evaluated in the body of the function in the order of the argument declarations. For this reason default values have access to previously declared arguments.
```yuescript
some_args = (x = 100, y = x + 1000) ->
print x + y
```
## Considerations
Because of the expressive parentheses-less way of calling functions, some restrictions must be put in place to avoid parsing ambiguity involving whitespace.
The minus sign plays two roles, a unary negation operator and a binary subtraction operator. Consider how the following examples compile:
```yuescript
a = x - 10
b = x-10
c = x -y
d = x- z
```
The precedence of the first argument of a function call can be controlled using whitespace if the argument is a literal string. In Lua, it is common to leave off parentheses when calling a function with a single string or table literal.
When there is no space between a variable and a string literal, the function call takes precedence over any following expressions. No other arguments can be passed to the function when it is called this way.
Where there is a space following a variable and a string literal, the function call acts as show above. The string literal belongs to any following expressions (if they exist), which serves as the argument list.
```yuescript
x = func"hello" + 100
y = func "hello" + 100
```
## Multi-line arguments
When calling functions that take a large number of arguments, it is convenient to split the argument list over multiple lines. Because of the white-space sensitive nature of the language, care must be taken when splitting up the argument list.
If an argument list is to be continued onto the next line, the current line must end in a comma. And the following line must be indented more than the current indentation. Once indented, all other argument lines must be at the same level of indentation to be part of the argument list
```yuescript
my_func 5, 4, 3,
8, 9, 10
cool_func 1, 2,
3, 4,
5, 6,
7, 8
```
This type of invocation can be nested. The level of indentation is used to determine to which function the arguments belong to.
```yuescript
my_func 5, 6, 7,
6, another_func 6, 7, 8,
9, 1, 2,
5, 4
```
Because tables also use the comma as a delimiter, this indentation syntax is helpful for letting values be part of the argument list instead of being part of the table.
```yuescript
x = [
1, 2, 3, 4, a_func 4, 5,
5, 6,
8, 9, 10
]
```
Although uncommon, notice how we can give a deeper indentation for function arguments if we know we will be using a lower indentation further on.
```yuescript
y = [ my_func 1, 2, 3,
4, 5,
5, 6, 7
]
```
The same thing can be done with other block level statements like conditionals. We can use indentation level to determine what statement a value belongs to:
```yuescript
if func 1, 2, 3,
"hello",
"world"
print "hello"
print "I am inside if"
if func 1, 2, 3,
"hello",
"world"
print "hello"
print "I am inside if"
```
## Parameter Destructuring
YueScript now supports destructuring function parameters when the argument is an object. Two forms of destructuring table literals are available:
- **Curly-brace wrapped literals/object parameters**, allowing optional default values when fields are missing (e.g., `{:a, :b}`, `{a: a1 = 123}`).
- **Unwrapped simple table syntax**, starting with a sequence of key-value or shorthand bindings and continuing until another expression terminates it (e.g., `:a, b: b1, :c`). This form extracts multiple fields from the same object.
```yuescript
f1 = (:a, :b, :c) ->
print a, b, c
f1 a: 1, b: "2", c: {}
f2 = ({a: a1 = 123, :b = 'abc'}, c = {}) ->
print a1, b, c
arg1 = {a: 0}
f2 arg1, arg2
```
## Prefixed Return Expression
When working with deeply nested function bodies, it can be tedious to maintain readability and consistency of the return value. To address this, YueScript introduces the **Prefixed Return Expression** syntax. Its form is as follows:
```yuescript
findFirstEven = (list): nil ->
for item in *list
if type(item) == "table"
for sub in *item
if sub % 2 == 0
return sub
```
This is equivalent to:
```yuescript
findFirstEven = (list) ->
for item in *list
if type(item) == "table"
for sub in *item
if sub % 2 == 0
return sub
nil
```
The only difference is that you can move the final return expression before the `->` or `=>` token to indicate the function’s implicit return value as the last statement. This way, even in functions with multiple nested loops or conditional branches, you no longer need to write a trailing return expression at the end of the function body, making the logic structure more straightforward and easier to follow.
## Named Varargs
You can use the `(...t) ->` syntax to automatically store varargs into a named table. This table will contain all passed arguments (including `nil` values), and the `n` field of the table will store the actual number of arguments passed (including `nil` values).
```yuescript
f = (...t) ->
print "argument count:", t.n
print "table length:", #t
for i = 1, t.n
print t[i]
f 1, 2, 3
f "a", "b", "c", "d"
f!
-- Handling cases with nil values
process = (...args) ->
sum = 0
for i = 1, args.n
if args[i] != nil and type(args[i]) == "number"
sum += args[i]
sum
process 1, nil, 3, nil, 5
```
# Whitespace
YueScript is a whitespace significant language. You have to write some code block in the same indent with space **' '** or tab **'\t'** like function body, value list and some control blocks. And expressions containing different whitespaces might mean different things. Tab is treated like 4 space, but it's better not mix the use of spaces and tabs.
## Statement Separator
A statement normally ends at a line break. You can also use a semicolon `;` to explicitly terminate a statement, which allows writing multiple statements on the same line:
```yuescript
a = 1; b = 2; print a + b
```
## Multiline Chaining
You can write multi-line chaining function calls with a same indent.
```yuescript
Rx.Observable
.fromRange 1, 8
\filter (x) -> x % 2 == 0
\concat Rx.Observable.of 'who do we appreciate'
\map (value) -> value .. '!'
\subscribe print
```
# Comment
```yuescript
-- I am a comment
str = --[[
This is a multi-line comment.
It's OK.
]] strA \ -- comment 1
.. strB \ -- comment 2
.. strC
func --[[port]] 3000, --[[ip]] "192.168.1.1"
```
# Attributes
Syntax support for Lua 5.4 attributes. And you can still use both the `const` and `close` declaration and get constant check and scoped callback working when targeting Lua versions below 5.4.
```yuescript
const a = 123
close _ = <close>: -> print "Out of scope."
```
You can do desctructuring with variables attributed as constant.
```yuescript
const {:a, :b, c, d} = tb
-- a = 1
```
You can also declare a global variable to be `const`.
```yuescript
global const Constant = 123
-- Constant = 1
```
# Operator
All of Lua's binary and unary operators are available. Additionally **!=** is as an alias for **~=**, and either **\\** or **::** can be used to write a chaining function call like `tb\func!` or `tb::func!`. And Yuescipt offers some other special operators to write more expressive codes.
```yuescript
tb\func! if tb ~= nil
tb::func! if tb != nil
```
## Chaining Comparisons
Comparisons can be arbitrarily chained:
```yuescript
print 1 < 2 <= 2 < 3 == 3 > 2 >= 1 == 1 < 3 != 5
-- output: true
a = 5
print 1 <= a <= 10
-- output: true
```
Note the evaluation behavior of chained comparisons:
```yuescript
v = (x) ->
print x
x
print v(1) < v(2) <= v(3)
--[[
output:
2
1
3
true
]]
print v(1) > v(2) <= v(3)
--[[
output:
2
1
false
]]
```
The middle expression is only evaluated once, rather than twice as it would be if the expression were written as `v(1) < v(2) and v(2) <= v(3)`. However, the order of evaluations in a chained comparison is undefined. It is strongly recommended not to use expressions with side effects (such as printing) in chained comparisons. If side effects are required, the short-circuit `and` operator should be used explicitly.
## Table Appending
The **[] =** operator is used to append values to tables.
```yuescript
tab = []
tab[] = "Value"
```
You can also use the spread operator `...` to append all elements from one list to another:
```yuescript
tbA = [1, 2, 3]
tbB = [4, 5, 6]
tbA[] = ...tbB
-- tbA is now [1, 2, 3, 4, 5, 6]
```
## Table Spreading
You can concatenate array tables or hash tables using spread operator `...` before expressions in table literals.
When spreading into a brace table literal (for example, `{...other}`), both the array part and hash part of the Lua table are copied.
```yuescript
parts =
* "shoulders"
* "knees"
lyrics =
* "head"
* ...parts
* "and"
* "toes"
copy = {...other}
a = {1, 2, 3, x: 1}
b = {4, 5, y: 1}
merge = {...a, ...b}
```
### List Table Spreading
When spreading into a bracket table literal (for example, `[...other,]`), only the array part is copied.
```yuescript
source = {1, 2, 3, name: "Yue"}
fullCopy = {...source}
listCopy = [...source,]
-- fullCopy => {1, 2, 3, name: "Yue"}
-- listCopy => [1, 2, 3]
```
## Table Reversed Indexing
You can use the **#** operator to get the last elements of a table.
```yuescript
last = data.items[#]
second_last = data.items[#-1]
data.items[#] = 1
```
## Metatable
The **<>** operator can be used as a shortcut for metatable manipulation.
### Metatable Creation
Create normal table with empty bracekets **<>** or metamethod key which is surrounded by **<>**.
```yuescript
mt = {}
add = (right) => <>: mt, value: @value + right.value
mt.__add = add
a = <>: mt, value: 1
-- set field with variable of the same name
b = :<add>, value: 2
c = <add>: mt.__add, value: 3
d = a + b + c
print d.value
close _ = <close>: -> print "out of scope"
```
### Metatable Accessing
Accessing metatable with **<>** or metamethod name surrounded by **<>** or writing some expression in **<>**.
```yuescript
-- create with metatable containing field "value"
tb = <"value">: 123
tb.<index> = tb.<>
print tb.value
tb.<> = __index: {item: "hello"}
print tb.item
```
### Metatable Destructure
Destruct metatable with metamethod key surrounded by **<>**.
```yuescript
{item, :new, :<close>, <index>: getter} = tb
print item, new, close, getter
```
## Existence
The **?** operator can be used in a variety of contexts to check for existence.
```yuescript
func?!
print abc?["hello world"]?.xyz
x = tab?.value
len = utf8?.len or string?.len or (o) -> #o
if print and x?
print x
with? io.open "test.txt", "w"
\write "hello"
\close!
```
## Piping
Instead of a series of nested function calls, you can pipe values with operator **|>**.
```yuescript
"hello" |> print
1 |> print 2 -- insert pipe item as the first argument
2 |> print 1, _, 3 -- pipe with a placeholder
-- pipe expression in multiline
readFile "example.txt"
|> extract language, {}
|> parse language
|> emit
|> render
|> print
```
## Nil Coalescing
The nil-coalescing operator **??** returns the value of its left-hand operand if it isn't **nil**; otherwise, it evaluates the right-hand operand and returns its result. The **??** operator doesn't evaluate its right-hand operand if the left-hand operand evaluates to non-nil.
```yuescript
local a, b, c, d
a = b ?? c ?? d
func a ?? {}
a ??= false
```
## Implicit Object
You can write a list of implicit structures that starts with the symbol **\*** or **-** inside a table block. If you are creating implicit object, the fields of the object must be with the same indent.
```yuescript
-- assignment with implicit object
list =
* 1
* 2
* 3
-- function call with implicit object
func
* 1
* 2
* 3
-- return with implicit object
f = ->
return
* 1
* 2
* 3
-- table with implicit object
tb =
name: "abc"
values:
- "a"
- "b"
- "c"
objects:
- name: "a"
value: 1
func: => @value + 1
tb:
fieldA: 1
- name: "b"
value: 2
func: => @value + 2
tb: { }
```
# Literals
All of the primitive literals in Lua can be used. This applies to numbers, strings, booleans, and **nil**.
Unlike Lua, Line breaks are allowed inside of single and double quote strings without an escape sequence:
```yuescript
some_string = "Here is a string
that has a line break in it."
-- You can mix expressions into string literals using #{} syntax.
-- String interpolation is only available in double quoted strings.
print "I am #{math.random! * 100}% sure."
```
## Number Literals
You can use underscores in a number literal to increase readability.
```yuescript
integer = 1_000_000
hex = 0xEF_BB_BF
binary = 0B10011
```
## YAML Multiline String
The `|` prefix introduces a YAML-style multiline string literal:
```yuescript
str = |
key: value
list:
- item1
- #{expr}
```
This allows writing structured multiline text conveniently. All line breaks and indentation are preserved relative to the first non-empty line, and expressions inside `#{...}` are interpolated automatically as `tostring(expr)`.
YAML Multiline String automatically detects the common leading whitespace prefix (minimum indentation across all non-empty lines) and removes it from all lines. This makes it easy to indent your code visually without affecting the resulting string content.
```yuescript
fn = ->
str = |
foo:
bar: baz
return str
```
Internal indentation is preserved relative to the removed common prefix, allowing clean nested structures.
All special characters like quotes (`"`) and backslashes (`\`) in the YAMLMultiline block are automatically escaped so that the generated Lua string is syntactically valid and behaves as expected.
```yuescript
str = |
path: "C:\Program Files\App"
note: 'He said: "#{Hello}!"'
```
# Module
## Import
The import statement is a syntax sugar for requiring a module or help extracting items from an imported module. The imported items are const by default.
```yuescript
-- used as table destructuring
do
import insert, concat from table
-- report error when assigning to insert, concat
import C, Ct, Cmt from require "lpeg"
-- shortcut for implicit requiring
import x, y, z from 'mymodule'
-- import with Python style
from 'module' import a, b, c
-- shortcut for requring a module
do
import 'module'
import 'module_x'
import "d-a-s-h-e-s"
import "module.part"
-- requring module with aliasing or table destructuring
do
import "player" as PlayerModule
import "lpeg" as :C, :Ct, :Cmt
import "export" as {one, two, Something:{umm:{ch}}}
```
## Import Global
You can import specific globals into local variables with `import`. When importing a chain of global variable accessings, the last field will be assigned to the local variable.
```yuescript
do
import tostring
import table.concat
print concat ["a", tostring 1]
```
### Automatic Global Variable Import
You can place `import global` at the top of a block to automatically import all names that have not been explicitly declared or assigned in the current scope as globals. These implicit imports are treated as local consts that reference the corresponding globals at the position of the statement.
Names that are explicitly declared as globals in the same scope will not be imported, so you can still assign to them.
```yuescript
do
import global
print "hello"
math.random 3
-- print = nil -- error: imported globals are const
do
-- explicit global variable will not be imported
import global
global FLAG
print FLAG
FLAG = 123
```
## Export
The export statement offers a concise way to define modules.
### Named Export
Named export will define a local variable as well as adding a field in the exported table.
```yuescript
export a, b, c = 1, 2, 3
export cool = "cat"
export What = if this
"abc"
else
"def"
export y = ->
hallo = 3434
export class Something
umm: "cool"
```
Doing named export with destructuring.
```yuescript
export :loadstring, to_lua: tolua = yue
export {itemA: {:fieldA = 'default'}} = tb
```
Export named items from module without creating local variables.
```yuescript
export.itemA = tb
export.<index> = items
export["a-b-c"] = 123
```
### Unnamed Export
Unnamed export will add the target item into the array part of the exported table.
```yuescript
d, e, f = 3, 2, 1
export d, e, f
export if this
123
else
456
export with tmp
j = 2000
```
### Default Export
Using the **default** keyword in export statement to replace the exported table with any thing.
```yuescript
export default ->
print "hello"
123
```
# License: MIT
Copyright (c) 2017-2026 Li Jin \<dragon-fly@qq.com\>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
# The YueScript Library
Access it by `local yue = require("yue")` in Lua.
## yue
**Description:**
The YueScript language library.
### version
**Type:** Field.
**Description:**
The YueScript version.
**Signature:**
```lua
version: string
```
### dirsep
**Type:** Field.
**Description:**
The file separator for the current platform.
**Signature:**
```lua
dirsep: string
```
### yue_compiled
**Type:** Field.
**Description:**
The compiled module code cache.
**Signature:**
```lua
yue_compiled: {string: string}
```
### to_lua
**Type:** Function.
**Description:**
The YueScript compiling function. It compiles the YueScript code to Lua code.
**Signature:**
```lua
to_lua: function(code: string, config?: Config):
--[[codes]] string | nil,
--[[error]] string | nil,
--[[globals]] {{string, integer, integer}} | nil
```
**Parameters:**
| Parameter | Type | Description |
| --------- | ------ | -------------------------------- |
| code | string | The YueScript code. |
| config | Config | [Optional] The compiler options. |
**Returns:**
| Return Type | Description |
| ----------------------------------- | ----------------------------------------------------------------------------------------------------------------------------- |
| string \| nil | The compiled Lua code, or nil if the compilation failed. |
| string \| nil | The error message, or nil if the compilation succeeded. |
| {{string, integer, integer}} \| nil | The global variables appearing in the code (with name, row and column), or nil if the compiler option `lint_global` is false. |
### file_exist
**Type:** Function.
**Description:**
The source file existence checking function. Can be overridden to customize the behavior.
**Signature:**
```lua
file_exist: function(filename: string): boolean
```
**Parameters:**
| Parameter | Type | Description |
| --------- | ------ | -------------- |
| filename | string | The file name. |
**Returns:**
| Return Type | Description |
| ----------- | ------------------------ |
| boolean | Whether the file exists. |
### read_file
**Type:** Function.
**Description:**
The source file reading function. Can be overridden to customize the behavior.
**Signature:**
```lua
read_file: function(filename: string): string
```
**Parameters:**
| Parameter | Type | Description |
| --------- | ------ | -------------- |
| filename | string | The file name. |
**Returns:**
| Return Type | Description |
| ----------- | ----------------- |
| string | The file content. |
### insert_loader
**Type:** Function.
**Description:**
Insert the YueScript loader to the package loaders (searchers).
**Signature:**
```lua
insert_loader: function(pos?: integer): boolean
```
**Parameters:**
| Parameter | Type | Description |
| --------- | ------- | ----------------------------------------------------------- |
| pos | integer | [Optional] The position to insert the loader. Default is 3. |
**Returns:**
| Return Type | Description |
| ----------- | -------------------------------------------------------------------------------------------- |
| boolean | Whether the loader is inserted successfully. It will fail if the loader is already inserted. |
### remove_loader
**Type:** Function.
**Description:**
Remove the YueScript loader from the package loaders (searchers).
**Signature:**
```lua
remove_loader: function(): boolean
```
**Returns:**
| Return Type | Description |
| ----------- | --------------------------------------------------------------------------------------- |
| boolean | Whether the loader is removed successfully. It will fail if the loader is not inserted. |
### loadstring
**Type:** Function.
**Description:**
Loads YueScript code from a string into a function.
**Signature:**
```lua
loadstring: function(input: string, chunkname: string, env: table, config?: Config):
--[[loaded function]] nil | function(...: any): (any...),
--[[error]] string | nil
```
**Parameters:**
| Parameter | Type | Description |
| --------- | ------ | -------------------------------- |
| input | string | The YueScript code. |
| chunkname | string | The name of the code chunk. |
| env | table | The environment table. |
| config | Config | [Optional] The compiler options. |
**Returns:**
| Return Type | Description |
| --------------- | --------------------------------------------------- |
| function \| nil | The loaded function, or nil if the loading failed. |
| string \| nil | The error message, or nil if the loading succeeded. |
### loadstring
**Type:** Function.
**Description:**
Loads YueScript code from a string into a function.
**Signature:**
```lua
loadstring: function(input: string, chunkname: string, config?: Config):
--[[loaded function]] nil | function(...: any): (any...),
--[[error]] string | nil
```
**Parameters:**
| Parameter | Type | Description |
| --------- | ------ | -------------------------------- |
| input | string | The YueScript code. |
| chunkname | string | The name of the code chunk. |
| config | Config | [Optional] The compiler options. |
**Returns:**
| Return Type | Description |
| --------------- | --------------------------------------------------- |
| function \| nil | The loaded function, or nil if the loading failed. |
| string \| nil | The error message, or nil if the loading succeeded. |
### loadstring
**Type:** Function.
**Description:**
Loads YueScript code from a string into a function.
**Signature:**
```lua
loadstring: function(input: string, config?: Config):
--[[loaded function]] nil | function(...: any): (any...),
--[[error]] string | nil
```
**Parameters:**
| Parameter | Type | Description |
| --------- | ------ | -------------------------------- |
| input | string | The YueScript code. |
| config | Config | [Optional] The compiler options. |
**Returns:**
| Return Type | Description |
| --------------- | --------------------------------------------------- |
| function \| nil | The loaded function, or nil if the loading failed. |
| string \| nil | The error message, or nil if the loading succeeded. |
### loadfile
**Type:** Function.
**Description:**
Loads YueScript code from a file into a function.
**Signature:**
```lua
loadfile: function(filename: string, env: table, config?: Config):
nil | function(...: any): (any...),
string | nil
```
**Parameters:**
| Parameter | Type | Description |
| --------- | ------ | -------------------------------- |
| filename | string | The file name. |
| env | table | The environment table. |
| config | Config | [Optional] The compiler options. |
**Returns:**
| Return Type | Description |
| --------------- | --------------------------------------------------- |
| function \| nil | The loaded function, or nil if the loading failed. |
| string \| nil | The error message, or nil if the loading succeeded. |
### loadfile
**Type:** Function.
**Description:**
Loads YueScript code from a file into a function.
**Signature:**
```lua
loadfile: function(filename: string, config?: Config):
nil | function(...: any): (any...),
string | nil
```
**Parameters:**
| Parameter | Type | Description |
| --------- | ------ | -------------------------------- |
| filename | string | The file name. |
| config | Config | [Optional] The compiler options. |
**Returns:**
| Return Type | Description |
| --------------- | --------------------------------------------------- |
| function \| nil | The loaded function, or nil if the loading failed. |
| string \| nil | The error message, or nil if the loading succeeded. |
### dofile
**Type:** Function.
**Description:**
Loads YueScript code from a file into a function and executes it.
**Signature:**
```lua
dofile: function(filename: string, env: table, config?: Config): any...
```
**Parameters:**
| Parameter | Type | Description |
| --------- | ------ | -------------------------------- |
| filename | string | The file name. |
| env | table | The environment table. |
| config | Config | [Optional] The compiler options. |
**Returns:**
| Return Type | Description |
| ----------- | ----------------------------------------- |
| any... | The return values of the loaded function. |
### dofile
**Type:** Function.
**Description:**
Loads YueScript code from a file into a function and executes it.
**Signature:**
```lua
dofile: function(filename: string, config?: Config): any...
```
**Parameters:**
| Parameter | Type | Description |
| --------- | ------ | -------------------------------- |
| filename | string | The file name. |
| config | Config | [Optional] The compiler options. |
**Returns:**
| Return Type | Description |
| ----------- | ----------------------------------------- |
| any... | The return values of the loaded function. |
### find_modulepath
**Type:** Function.
**Description:**
Resolves the YueScript module name to the file path.
**Signature:**
```lua
find_modulepath: function(name: string): string
```
**Parameters:**
| Parameter | Type | Description |
| --------- | ------ | ---------------- |
| name | string | The module name. |
**Returns:**
| Return Type | Description |
| ----------- | -------------- |
| string | The file path. |
### pcall
**Type:** Function.
**Description:**
Calls a function in protected mode.
Catches any errors and returns a status code and results or error object.
Rewrites the error line number to the original line number in the YueScript code when errors occur.
**Signature:**
```lua
pcall: function(f: function, ...: any): boolean, any...
```
**Parameters:**
| Parameter | Type | Description |
| --------- | -------- | ---------------------------------- |
| f | function | The function to call. |
| ... | any | Arguments to pass to the function. |
**Returns:**
| Return Type | Description |
| ------------ | ------------------------------------------------- |
| boolean, ... | Status code and function results or error object. |
### require
**Type:** Function.
**Description:**
Loads a given module. Can be either a Lua module or a YueScript module.
Rewrites the error line number to the original line number in the YueScript code if the module is a YueScript module and loading fails.
**Signature:**
```lua
require: function(name: string): any...
```
**Parameters:**
| Parameter | Type | Description |
| --------- | ------ | ------------------------------- |
| modname | string | The name of the module to load. |
**Returns:**
| Return Type | Description |
| ----------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| any | The value stored at package.loaded[modname] if the module is already loaded.Otherwise, tries to find a loader and returns the final value of package.loaded[modname] and a loader data as a second result. |
### p
**Type:** Function.
**Description:**
Inspects the structures of the passed values and prints string representations.
**Signature:**
```lua
p: function(...: any)
```
**Parameters:**
| Parameter | Type | Description |
| --------- | ---- | ---------------------- |
| ... | any | The values to inspect. |
### options
**Type:** Field.
**Description:**
The current compiler options.
**Signature:**
```lua
options: Config.Options
```
### traceback
**Type:** Function.
**Description:**
The traceback function that rewrites the stack trace line numbers to the original line numbers in the YueScript code.
**Signature:**
```lua
traceback: function(message: string): string
```
**Parameters:**
| Parameter | Type | Description |
| --------- | ------ | ---------------------- |
| message | string | The traceback message. |
**Returns:**
| Return Type | Description |
| ----------- | -------------------------------- |
| string | The rewritten traceback message. |
### is_ast
**Type:** Function.
**Description:**
Checks whether the code matches the specified AST.
**Signature:**
```lua
is_ast: function(astName: string, code: string): boolean
```
**Parameters:**
| Parameter | Type | Description |
| --------- | ------ | ------------- |
| astName | string | The AST name. |
| code | string | The code. |
**Returns:**
| Return Type | Description |
| ----------- | --------------------------------- |
| boolean | Whether the code matches the AST. |
### AST
**Type:** Field.
**Description:**
The AST type definition with name, row, column and sub nodes.
**Signature:**
```lua
type AST = {string, integer, integer, any}
```
### to_ast
**Type:** Function.
**Description:**
Converts the code to the AST.
**Signature:**
```lua
to_ast: function(code: string, flattenLevel?: number, astName?: string, reserveComment?: boolean):
--[[AST]] AST | nil,
--[[error]] nil | string
```
**Parameters:**
| Parameter | Type | Description |
| -------------- | ------- | --------------------------------------------------------------------------------------------- |
| code | string | The code. |
| flattenLevel | integer | [Optional] The flatten level. Higher level means more flattening. Default is 0. Maximum is 2. |
| astName | string | [Optional] The AST name. Default is "File". |
| reserveComment | boolean | [Optional] Whether to reserve the original comments. Default is false. |
**Returns:**
| Return Type | Description |
| ------------- | ------------------------------------------------------ |
| AST \| nil | The AST, or nil if the conversion failed. |
| string \| nil | The error message, or nil if the conversion succeeded. |
### format
**Type:** Function.
**Description:**
Formats the YueScript code.
**Signature:**
```lua
format: function(code: string, tabSize?: number, reserveComment?: boolean): string
```
**Parameters:**
| Parameter | Type | Description |
| -------------- | ------- | --------------------------------------------------------------------- |
| code | string | The code. |
| tabSize | integer | [Optional] The tab size. Default is 4. |
| reserveComment | boolean | [Optional] Whether to reserve the original comments. Default is true. |
**Returns:**
| Return Type | Description |
| ----------- | ------------------- |
| string | The formatted code. |
### \_\_call
**Type:** Metamethod.
**Description:**
Requires the YueScript module.
Rewrites the error line number to the original line number in the YueScript code when loading fails.
**Signature:**
```lua
metamethod __call: function(self: yue, module: string): any...
```
**Parameters:**
| Parameter | Type | Description |
| --------- | ------ | ---------------- |
| module | string | The module name. |
**Returns:**
| Return Type | Description |
| ----------- | ----------------- |
| any | The module value. |
## Config
**Description:**
The compiler compile options.
### lint_global
**Type:** Field.
**Description:**
Whether the compiler should collect the global variables appearing in the code.
**Signature:**
```lua
lint_global: boolean
```
### implicit_return_root
**Type:** Field.
**Description:**
Whether the compiler should do an implicit return for the root code block.
**Signature:**
```lua
implicit_return_root: boolean
```
### reserve_line_number
**Type:** Field.
**Description:**
Whether the compiler should reserve the original line number in the compiled code.
**Signature:**
```lua
reserve_line_number: boolean
```
### reserve_comment
**Type:** Field.
**Description:**
Whether the compiler should reserve the original comments in the compiled code.
**Signature:**
```lua
reserve_comment: boolean
```
### space_over_tab
**Type:** Field.
**Description:**
Whether the compiler should use the space character instead of the tab character in the compiled code.
**Signature:**
```lua
space_over_tab: boolean
```
### same_module
**Type:** Field.
**Description:**
Whether the compiler should treat the code to be compiled as the same currently being compiled module. For internal use only.
**Signature:**
```lua
same_module: boolean
```
### line_offset
**Type:** Field.
**Description:**
Whether the compiler error message should include the line number offset. For internal use only.
**Signature:**
```lua
line_offset: integer
```
### yue.Config.LuaTarget
**Type:** Enumeration.
**Description:**
The target Lua version enumeration.
**Signature:**
```lua
enum LuaTarget
"5.1"
"5.2"
"5.3"
"5.4"
"5.5"
end
```
### options
**Type:** Field.
**Description:**
The extra options to be passed to the compilation function.
**Signature:**
```lua
options: Options
```
## Options
**Description:**
The extra compiler options definition.
### target
**Type:** Field.
**Description:**
The target Lua version for the compilation.
**Signature:**
```lua
target: LuaTarget
```
### path
**Type:** Field.
**Description:**
The extra module search path.
**Signature:**
```lua
path: string
```
### dump_locals
**Type:** Field.
**Description:**
Whether to dump the local variables in the traceback error message. Default is false.
**Signature:**
```lua
dump_locals: boolean
```
### simplified
**Type:** Field.
**Description:**
Whether to simplify the error message. Default is true.
**Signature:**
```lua
simplified: boolean
```
|