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

<BODY BGCOLOR="#FFFFFF">

<HR>
<H1>
<IMG SRC="logo.gif" ALT="Lua" ALIGN="bottom">
Reference Manual of the Programming Language
<A HREF="http://www.tecgraf.puc-rio.br/lua/">Lua</A>
4.0
</H1>

<!--  $Id: manual.tex,v 1.45 2000/10/31 18:20:01 roberto Exp roberto $ -->
<P>
<P>
<!-- ====================================================================== -->
<HR>
<A NAME="1."></A>
<H1>1 - Introduction</H1>
<P>
Lua is an extension programming language designed to support
general procedural programming with data description
facilities.
Lua is intended to be used as a powerful, light-weight
configuration language for any program that needs one.
<P>
Lua is implemented as a library, written in C.
Being an extension language, Lua has no notion of a ``main'' program:
it only works <EM>embedded</EM> in a host client,
called the <EM>embedding</EM> program.
This host program can invoke functions to execute a piece of
code in Lua, can write and read Lua variables,
and can register C&nbsp;functions to be called by Lua code.
Through the use of C&nbsp;functions, Lua can be augmented to cope with
a wide range of different domains,
thus creating customized programming languages sharing a syntactical framework.
<P>
Lua is free-distribution software,
and is provided as usual with no guarantees,
as stated in its copyright notice.
The implementation described in this manual is available
at the following URL's:
<PRE>
       <A HREF="http://www.tecgraf.puc-rio.br/lua/">http://www.tecgraf.puc-rio.br/lua/</A>
       <A HREF="ftp://ftp.tecgraf.puc-rio.br/pub/lua/">ftp://ftp.tecgraf.puc-rio.br/pub/lua/</A>
</PRE>
<P>
Like any other reference manual,
this document is dry in places.
For a discussion of the decisions behind the design of Lua,
see the papers below,
which are available at the web site above.
<UL>
<LI>
R.&nbsp;Ierusalimschy, L.&nbsp;H.&nbsp;de Figueiredo, and W.&nbsp;Celes.
Lua-an extensible extension language.
<EM>Software: Practice &amp; Experience</EM> <B>26</B> #6 (1996) 635--652.
<LI>
L.&nbsp;H.&nbsp;de Figueiredo, R.&nbsp;Ierusalimschy, and W.&nbsp;Celes.
The design and implementation of a language for extending applications.
<EM>Proceedings of XXI Brazilian Seminar on Software and Hardware</EM> (1994) 273--283.
<LI>
L.&nbsp;H.&nbsp;de Figueiredo, R.&nbsp;Ierusalimschy, and W.&nbsp;Celes.
Lua: an extensible embedded language.
<EM>Dr. Dobb's Journal</EM> <B>21</B> #12 (Dec 1996) 26--33.
</UL>
<P>
<!-- ====================================================================== -->
<HR>
<A NAME="2."></A>
<H1>2 - Environment and Chunks</H1>
<P>
All statements in Lua are executed in a <A NAME="global environment"><EM>global environment</EM></A>.
This environment is initialized with a call from the embedding program to
<CODE>lua_open</CODE> and
persists until a call to <CODE>lua_close</CODE>,
or the end of the embedding program.
If necessary,
the host programmer can create multiple independent global
environments, and freely switch between them (see Section&nbsp;<A HREF="#mangstate">5.1</A>).
<P>
The global environment can be manipulated by Lua code or
by the embedding program,
which can read and write global variables
using API functions from the library that implements Lua.
<P>
<A NAME="Global variables">Global variables</A> in Lua do not need to be declared.
Any variable is assumed to be global unless explicitly declared local
(see Section&nbsp;<A HREF="#localvar">4.4.6</A>).
Before the first assignment, the value of a global variable is <B>nil</B> 
(this default can be changed; see Section&nbsp;<A HREF="#tag-method">4.8</A>).
A table is used to keep all global names and values
(tables are explained in Section&nbsp;<A HREF="#TypesSec">3</A>).
<P>
The unit of execution of Lua is called a <A NAME="chunk"><EM>chunk</EM></A>.
A chunk is simply a sequence of statements,
which are executed sequentially.
Each statement can be optionally followed by a semicolon:
<PRE>
       chunk ::= {stat [`<B>;</B>']}
</PRE>
Statements are described in Section&nbsp;<A HREF="#stats">4.4</A>.
(The notation above is the usual extended BNF,
in which
{<EM>a</EM>} means 0 or more <EM>a</EM>'s,
[<EM>a</EM>] means an optional <EM>a</EM>, and
(<EM>a</EM>)+ means one or more <EM>a</EM>'s.
The complete syntax of Lua is given in <A HREF="BNF">BNF</A>).
<P>
A chunk may be stored in a file or in a string inside the host program.
When a chunk is executed, first it is pre-compiled into bytecodes for
a virtual machine, and then the statements are executed in sequential order,
by simulating the virtual machine.
All modifications a chunk effects on the global environment persist
after the chunk ends.
<P>
Chunks may also be pre-compiled into binary form and stored in files;
see program <A NAME="luac"><TT><A HREF="luac.html">luac</A></TT></A> for details.
Text files with chunks and their binary pre-compiled forms
are interchangeable.
Lua automatically detects the file type and acts accordingly.
<A NAME="pre-compilation"></A>
<P>
<A NAME="TypesSec"></A>
<!-- ====================================================================== -->
<HR>
<A NAME="3."></A>
<H1>3 - Types and Tags</H1> 
<P>
Lua is a <EM>dynamically typed language</EM>.
This means that
variables do not have types; only values do.
Therefore, there are no type definitions in the language.
All values carry their own type.
Besides a type, all values also have a <A NAME="tag"><EM>tag</EM></A>.
<P>
There are six <A NAME="basic types">basic types</A> in Lua: <A NAME="nil"><EM>nil</EM></A>, <A NAME="number"><EM>number</EM></A>,
<A NAME="string"><EM>string</EM></A>, <A NAME="function"><EM>function</EM></A>, <A NAME="userdata"><EM>userdata</EM></A>, and <A NAME="table"><EM>table</EM></A>.
<EM>Nil</EM> is the type of the value <B>nil</B>,
whose main property is to be different from any other value.
<EM>Number</EM> represents real (double-precision floating-point) numbers,
while <EM>string</EM> has the usual meaning.
<A NAME="eight-bit clean"></A>
Lua is 8-bit clean,
and so strings may contain any 8-bit character,
including embedded zeros (<CODE>'\0'</CODE>) (see Section&nbsp;<A HREF="#lexical">4.1</A>).
The <CODE>type</CODE> function returns a string describing the type
of a given value (see Section&nbsp;<A HREF="#pdf-type">6.1</A>).
<P>
Functions are considered <EM>first-class values</EM> in Lua.
This means that functions can be stored in variables,
passed as arguments to other functions, and returned as results.
Lua can call (and manipulate) functions written in Lua and
functions written in C.
The two kinds of functions can be distinguished by their tags:
all Lua functions have the same tag,
and all C&nbsp;functions have the same tag,
which is different from the tag of Lua functions.
The <CODE>tag</CODE> function returns the tag
of a given value (see Section&nbsp;<A HREF="#pdf-tag">6.1</A>).
<P>
The type <EM>userdata</EM> is provided to allow
arbitrary <A NAME="C pointers">C&nbsp;pointers</A> to be stored in Lua variables.
This type corresponds to a <CODE>void*</CODE>
and has no pre-defined operations in Lua,
except assignment and equality test.
However, by using <EM>tag methods</EM>,
the programmer can define operations for <EM>userdata</EM> values
(see Section&nbsp;<A HREF="#tag-method">4.8</A>).
<P>
The type <EM>table</EM> implements <A NAME="associative arrays">associative arrays</A>,
that is, <A NAME="arrays">arrays</A> that can be indexed not only with numbers,
but with any value (except <B>nil</B>).
Therefore, this type may be used not only to represent ordinary arrays,
but also symbol tables, sets, records, graphs, trees, etc.
Tables are the main data structuring mechanism in Lua.
To represent <A NAME="records">records</A>, Lua uses the field name as an index.
The language supports this representation by
providing <CODE>a.name</CODE> as syntactic sugar for <CODE>a["name"]</CODE>.
Tables may also carry <EM>methods</EM>:
Because functions are first class values,
table fields may contain functions.
The form <CODE>t:f(x)</CODE> is syntactic sugar for <CODE>t.f(t,x)</CODE>,
which calls the method <CODE>f</CODE> from the table <CODE>t</CODE> passing
the table itself as the first parameter (see Section&nbsp;<A HREF="#func-def">4.5.9</A>).
<P>
Note that tables are <EM>objects</EM>, and not values.
Variables do not contain tables, only <EM>references</EM> to them.
Assignment, parameter passing, and returns always manipulate references
to tables, and do not imply any kind of copy.
Moreover, tables must be explicitly created before used
(see Section&nbsp;<A HREF="#tableconstructor">4.5.7</A>).
<P>
Each of the types <EM>nil</EM>, <EM>number</EM>, and <EM>string</EM> has a different tag.
All values of each of these types have the same pre-defined tag.
As explained above,
values of type <EM>function</EM> can have two different tags,
depending on whether they are Lua functions or C&nbsp;functions.
Finally,
values of type <EM>userdata</EM> and <EM>table</EM> can have variable tags,
assigned by the programmer (see Section&nbsp;<A HREF="#tag-method">4.8</A>).
The <CODE>tag</CODE> function returns the tag of a given value.
User tags are created with the function <CODE>newtag</CODE>.
The <CODE>settag</CODE> function
is used to change the tag of a table (see Section&nbsp;<A HREF="#pdf-newtag">6.1</A>).
The tag of userdata values can only be set from&nbsp;C (see Section&nbsp;<A HREF="#C-tags">5.7</A>).
Tags are mainly used to select <EM>tag methods</EM> when
some events occur.
Tag methods are the main mechanism for extending the
semantics of Lua (see Section&nbsp;<A HREF="#tag-method">4.8</A>).
<P>
<!-- ====================================================================== -->
<HR>
<A NAME="4."></A>
<H1>4 - The Language</H1>
<P>
This section describes the lexis, the syntax, and the semantics of Lua.
<P>
<P>
<A NAME="lexical"></A>
<A NAME="4.1"></A>
<H2>4.1 - Lexical Conventions</H2> 
<P>
<A NAME="Identifiers"><EM>Identifiers</EM></A> in Lua can be any string of letters,
digits, and underscores,
not beginning with a digit.
This coincides with the definition of identifiers in most languages,
except that
the definition of letter depends on the current locale:
Any character considered alphabetic by the current locale
can be used in an identifier.
The following words are <EM>reserved</EM>, and cannot be used as identifiers:
<A NAME="reserved words"></A>
<PRE>
       and       break     do        else      elseif
       end       for       function  if        in
       local     nil       not       or        repeat
       return    then      until     while
</PRE>
<P>
Lua is a case-sensitive language:
<TT>and</TT> is a reserved word, but <TT>And</TT> and <TT>ánd</TT>
(if the locale permits) are two different, valid identifiers.
As a convention, identifiers starting with underscore followed by
uppercase letters (such as <CODE>_INPUT</CODE>)
are reserved for internal variables.
<P>
The following strings denote other <A NAME="tokens">tokens</A>:
<PRE>
       ~=    &lt;=    &gt;=    &lt;     &gt;     ==    =     +     -     *     /     
       (     )     {     }     [     ]     ;     ,     .     ..    ...
</PRE>
<P>
<A NAME="Literal strings"><EM>Literal strings</EM></A>
can be delimited by matching single or double quotes,
and can contain the C-like escape sequences
`<CODE>\a</CODE>' (bell),
`<CODE>\b</CODE>' (backspace),
`<CODE>\f</CODE>' (form feed),
`<CODE>\n</CODE>' (newline),
`<CODE>\r</CODE>' (carriage return),
`<CODE>\t</CODE>' (horizontal tab),
`<CODE>\v</CODE>' (vertical tab),
`<CODE>\\</CODE>' (backslash),
`<CODE>\"</CODE>' (double quote),
`<CODE>\'</CODE>' (single quote),
and `<CODE>\</CODE><EM>newline</EM>' (that is, a backslash followed by a real newline,
which  results in a newline in the string).
A character in a string may also be specified by its numerical value,
through the escape sequence `<CODE>\</CODE><EM>ddd</EM>',
where <EM>ddd</EM> is a sequence of up to three <EM>decimal</EM> digits.
Strings in Lua may contain any 8-bit value, including embedded zeros,
which can be specified as `<CODE>\000</CODE>'.
<P>
Literal strings can also be delimited by matching <CODE>[[</CODE> ... <CODE>]]</CODE>.
Literals in this bracketed form may run for several lines,
may contain nested <CODE>[[</CODE> ... <CODE>]]</CODE> pairs,
and do not interpret escape sequences.
This form is specially convenient for
writing strings that contain program pieces or
other quoted strings.
As an example, in a system using ASCII,
the following three literals are equivalent:
<PRE>
       1)   "alo\n123\""
       2)   '\97lo\10\04923"'
       3)   [[alo
            123"]]
</PRE>
<P>
<A NAME="Comments"><EM>Comments</EM></A> start anywhere outside a string with a
double hyphen (<CODE>--</CODE>) and run until the end of the line.
Moreover,
the first line of a chunk is skipped if it starts with <CODE>#</CODE>.
This facility allows the use of Lua as a script interpreter
in Unix systems (see Section&nbsp;<A HREF="#lua-sa">8</A>).
<P>
<A NAME="Numerical constants"><EM>Numerical constants</EM></A> may be written with an optional decimal part
and an optional decimal exponent.
Examples of valid numerical constants are
<PRE>
       3     3.0     3.1416  314.16e-2   0.31416E1
</PRE>
<P>
<A NAME="coercion"></A>
<A NAME="4.2"></A>
<H2>4.2 - Coercion</H2> 
<P>
Lua provides some automatic conversions between values at run time.
Any arithmetic operation applied to a string tries to convert
that string to a number, following the usual rules.
Conversely, whenever a number is used when a string is expected,
that number is converted to a string, in a reasonable format.
The format is chosen so that
a conversion from number to string then back to number
reproduces the original number <EM>exactly</EM>.
Thus,
the conversion does not necessarily produces nice-looking text for some numbers.
For complete control of how numbers are converted to strings,
use the <CODE>format</CODE> function (see Section&nbsp;<A HREF="#format">6.2</A>).
<P>
<P>
<A NAME="adjust"></A>
<A NAME="4.3"></A>
<H2>4.3 - Adjustment</H2> 
<P>
Functions in Lua can return many values.
Because there are no type declarations,
when a function is called
the system does not know how many values the function will return,
or how many parameters it needs.
Therefore, sometimes, a list of values must be <EM>adjusted</EM>, at run time,
to a given length.
If there are more values than are needed,
then the excess values are thrown away.
If there are less values than are needed,
then the list is extended with as many  <B>nil</B>'s as needed.
This adjustment occurs in multiple assignments (see Section&nbsp;<A HREF="#assignment">4.4.2</A>)
and in function calls (see Section&nbsp;<A HREF="#functioncall">4.5.8</A>).
<P>
<P>
<A NAME="stats"></A>
<A NAME="4.4"></A>
<H2>4.4 - Statements</H2>
<P>
Lua supports an almost conventional set of <A NAME="statements">statements</A>,
similar to those in Pascal or C.
The conventional commands include
assignment, control structures, and procedure calls.
Non-conventional commands include table constructors
(see Section&nbsp;<A HREF="#tableconstructor">4.5.7</A>)
and local variable declarations (see Section&nbsp;<A HREF="#localvar">4.4.6</A>).
<P>
<H3>4.4.1 - Blocks</H3>
A <A NAME="block">block</A> is a list of statements;
syntactically, a block is equal to a chunk:
<PRE>
       block ::= chunk
</PRE>
<P>
A block may be explicitly delimited:
<PRE>
       stat ::= <B>do</B> block <B>end</B>
</PRE>
Explicit blocks are useful
to control the scope of local variables (see Section&nbsp;<A HREF="#localvar">4.4.6</A>).
Explicit blocks are also sometimes used to
add a <B>return</B> or <B>break</B> statement in the middle
of another block (see Section&nbsp;<A HREF="#control">4.4.3</A>).
<P>
<A NAME="assignment"></A>
<H3>4.4.2 - <A NAME="Assignment</H3>">Assignment</H3></A> 
Lua allows <A NAME="multiple assignment">multiple assignment</A>.
Therefore, the syntax for assignment
defines a list of variables on the left side
and a list of expressions on the right side.
The elements in both lists are separated by commas:
<PRE>
       stat ::= varlist1 `<B>=</B>' explist1
       varlist1 ::= var {`<B>,</B>' var}
</PRE>
This statement first evaluates all values on the right side
and eventual indices on the left side,
and then makes the assignments.
So, the code
<PRE>
       i = 3
       i, a[i] = 4, 20
</PRE>
sets <CODE>a[3]</CODE> to 20, but does not affect <CODE>a[4]</CODE>
because the <CODE>i</CODE> in <CODE>a[i]</CODE> is evaluated
before it is assigned <CODE>4</CODE>.
<P>
Multiple assignment can be used to exchange two values, as in
<PRE>
       x, y = y, x
</PRE>
<P>
The two lists in a multiple assignment may have different lengths.
Before the assignment, the list of values is adjusted to
the length of the list of variables (see Section&nbsp;<A HREF="#adjust">4.3</A>).
<P>
A single name can denote a global variable, a local variable,
or a formal parameter:
<PRE>
       var ::= name
</PRE>
<P>
Square brackets are used to index a table:
<PRE>
       var ::= varorfunc `<B>[</B>' exp1 `<B>]</B>'
       varorfunc ::= var | functioncall
</PRE>
The <EM>varorfunc</EM> should result in a table value,
from where the field indexed by the expression <EM>exp1</EM>
value gets the assigned value.
<P>
The syntax <CODE>var.NAME</CODE> is just syntactic sugar for
<CODE>var["NAME"]</CODE>:
<PRE>
       var ::= varorfunc `<B>.</B>' name
</PRE>
<P>
The meaning of assignments and evaluations of global variables and
indexed variables can be changed by tag methods (see Section&nbsp;<A HREF="#tag-method">4.8</A>).
Actually,
an assignment <CODE>x = val</CODE>, where <CODE>x</CODE> is a global variable,
is equivalent to a call <CODE>setglobal("x", val)</CODE> and
an assignment <CODE>t[i] = val</CODE> is equivalent to
<CODE>settable_event(t,i,val)</CODE>.
See Section&nbsp;<A HREF="#tag-method">4.8</A> for a complete description of these functions
(<CODE>setglobal</CODE> is in the basic library;
<TT>settable_event</TT> is used for explanatory purposes only).
<P>
<A NAME="control"></A>
<H3>4.4.3 - Control Structures</H3>
The control structures
<B>if</B>, <B>while</B>, and <B>repeat</B> have the usual meaning and
familiar syntax
<A NAME="while-do statement"></A>
<A NAME="repeat-until statement"></A>
<A NAME="if-then-else statement"></A>
<PRE>
       stat ::= <B>while</B> exp1 <B>do</B> block <B>end</B>
       stat ::= <B>repeat</B> block <B>until</B> exp1
       stat ::= <B>if</B> exp1 <B>then</B> block {<B>elseif</B> exp1 <B>then</B> block} [<B>else</B> block] <B>end</B>
</PRE>
The <A NAME="condition expression">condition expression</A> <EM>exp1</EM> of a control structure may return any value.
All values different from <B>nil</B> are considered true;
only <B>nil</B> is considered false.
<P>
The <B>return</B> statement is used to return values
from a function or from a chunk.
<A NAME="return"></A>

<A NAME="return statement"></A>
Because functions or chunks may return more than one value,
the syntax for the <B>return</B> statement is
<PRE>
       stat ::= <B>return</B> [explist1]
</PRE>
<P>
The <B>break</B> statement can be used to terminate the execution of a loop,
skipping to the next statement after the loop:
<A NAME="break statement"></A>
<PRE>
       stat ::= <B>break</B>
</PRE>
A <B>break</B> ends the innermost enclosing loop
(<B>while</B>, <B>repeat</B>, or <B>for</B>).
<P>
For syntactic reasons, <B>return</B> and <B>break</B>
statements can only be written as the <EM>last</EM> statements of a block.
If it is really necessary to <B>return</B> or <B>break</B> in the
middle of a block,
an explicit inner block can used,
as in the idiom `<CODE>do return end</CODE>',
because now <B>return</B> is last statement in the inner block.
<P>
<A NAME="for"></A>
<H3>4.4.4 - For Statement</H3> <A NAME="for statement"></A>
<P>
The <B>for</B> statement has two forms,
one for numbers and one for tables.
The numerical <B>for</B> loop has the following syntax:
<PRE>
       stat ::= <B>for</B> name `<B>=</B>' exp1 `<B>,</B>' exp1 [`<B>,</B>' exp1] <B>do</B> block <B>end</B>
</PRE>
A <B>for</B> statement like
<PRE>
       for var = e1 ,e2, e3 do block end
</PRE>
is equivalent to the code:
<PRE>
       do
         local var, _limit, _step = tonumber(e1), tonumber(e2), tonumber(e3)
         if not (var and _limit and _step) then error() end
         while (_step&gt;0 and var&lt;=_limit) or (_step&lt;=0 and var&gt;=_limit) do
           block
           var = var+_step
         end
       end
</PRE>
Note the following:
<UL><LI>sep=0pt
<LI><CODE>_limit</CODE> and <CODE>_step</CODE> are invisible variables.
The names are here for explanatory purposes only.
<LI>The behavior is <EM>undefined</EM> if you assign to <CODE>var</CODE> inside
the block.
<LI>If the third expression (the step) is absent, then a step of&nbsp;1 is used.
<LI>Both the limit and the step are evaluated only once,
before the loop starts.
<LI>The variable <CODE>var</CODE> is local to the statement;
you cannot use its value after the <B>for</B> ends.
<LI>You can use <B>break</B> to exit a <B>for</B>.
If you need the value of the index,
assign it to another variable before breaking.
</UL>
<P>
The table <B>for</B> statement traverses all pairs
(index,value) of a given table.
It has the following syntax:
<PRE>
       stat ::= <B>for</B> name `<B>,</B>' name <B>in</B> exp1 <B>do</B> block <B>end</B>
</PRE>
A <B>for</B> statement like
<PRE>
       for index, value in exp do block end
</PRE>
is equivalent to the code:
<PRE>
       do
         local _t = exp
         local index, value = next(t, nil)
         while index do
           block
           index, value = next(t, index)
         end
       end
</PRE>
Note the following:
<UL><LI>sep=0pt
<LI><CODE>_t</CODE> is an invisible variable.
The name is here for explanatory purposes only.
<LI>The behavior is <EM>undefined</EM> if you assign to <CODE>index</CODE> inside
the block.
<LI>The behavior is <EM>undefined</EM> if you change
the table <CODE>_t</CODE> during the traversal.
<LI>The variables <CODE>index</CODE> and <CODE>value</CODE> are local to the statement;
you cannot use their values after the <B>for</B> ends.
<LI>You can use <B>break</B> to exit a <B>for</B>.
If you need the value of <CODE>index</CODE> or <CODE>value</CODE>,
assign them to other variables before breaking.
<LI>The order that table elements are traversed is undefined,
<EM>even for numerical indices</EM>.
If you want to traverse indices in numerical order,
use a numerical <B>for</B>.
</UL>
<P>
<P>
<A NAME="funcstat"></A>
<H3>4.4.5 - Function Calls as Statements</H3> 
Because of possible side-effects,
function calls can be executed as statements:
<PRE>
       stat ::= functioncall
</PRE>
In this case, all returned values are thrown away.
Function calls are explained in Section&nbsp;<A HREF="#functioncall">4.5.8</A>.
<P>
<A NAME="localvar"></A>
<H3>4.4.6 - Local Declarations</H3> 
<A NAME="Local variables">Local variables</A> may be declared anywhere inside a block.
The declaration may include an initial assignment:
<PRE>
       stat ::= <B>local</B> declist [init]
       declist ::= name {`<B>,</B>' name}
       init ::= `<B>=</B>' explist1
</PRE>
If present, an initial assignment has the same semantics
of a multiple assignment.
Otherwise, all variables are initialized with <B>nil</B>.
<P>
A chunk is also a block,
and so local variables can be declared outside any explicit block.
<P>
The scope of local variables begins <EM>after</EM>
the declaration and lasts until the end of the block.
Thus, the code
<CODE>local print=print</CODE>
creates a local variable called <CODE>print</CODE> whose
initial value is that of the <EM>global</EM> variable of the same name.
<P>
<P>
<A NAME="4.5"></A>
<H2>4.5 - Expressions</H2>
<P>
<H3>4.5.1 - <A NAME="Basic Expressions</H3>">Basic Expressions</H3></A>
The basic expressions in Lua are
<PRE>
       exp ::= `<B>(</B>' exp `<B>)</B>'
       exp ::= <B>nil</B>
       exp ::= number
       exp ::= literal
       exp ::= var
       exp ::= upvalue
       exp ::= function
       exp ::= functioncall
       exp ::= tableconstructor
</PRE>
<P>
Numbers (numerical constants) and
literal strings are explained in Section&nbsp;<A HREF="#lexical">4.1</A>;
variables are explained in Section&nbsp;<A HREF="#assignment">4.4.2</A>;
upvalues are explained in Section&nbsp;<A HREF="#upvalue">4.6</A>;
function definitions are explained in Section&nbsp;<A HREF="#func-def">4.5.9</A>;
function calls are explained in Section&nbsp;<A HREF="#functioncall">4.5.8</A>.
Table constructors are explained in Section&nbsp;<A HREF="#tableconstructor">4.5.7</A>.
<P>
An access to a global variable <CODE>x</CODE> is equivalent to a
call <CODE>getglobal("x")</CODE> and
an access to an indexed variable <CODE>t[i]</CODE> is equivalent to
a call <CODE>gettable_event(t,i)</CODE>.
See Section&nbsp;<A HREF="#tag-method">4.8</A> for a description of these functions
(<CODE>getglobal</CODE> is in the basic library;
<TT>gettable_event</TT> is used for explanatory purposes only).
<P>
The non-terminal <EM>exp1</EM> is used to indicate that the values
returned by an expression must be adjusted to one single value:
<PRE>
       exp1 ::= exp
</PRE>
<P>
<H3>4.5.2 - Arithmetic Operators</H3>
Lua supports the usual <A NAME="arithmetic operators">arithmetic operators</A>:
the binary <CODE>+</CODE> (addition),
<CODE>-</CODE> (subtraction), <CODE>*</CODE> (multiplication),
<CODE>/</CODE> (division), and <CODE>^</CODE> (exponentiation);
and unary <CODE>-</CODE> (negation).
If the operands are numbers, or strings that can be converted to
numbers (according to the rules given in Section&nbsp;<A HREF="#coercion">4.2</A>),
then all operations except exponentiation have the usual meaning.
Otherwise, an appropriate tag method is called (see Section&nbsp;<A HREF="#tag-method">4.8</A>).
An exponentiation always calls a tag method.
The standard mathematical library redefines this method for numbers,
giving the expected meaning to <A NAME="exponentiation">exponentiation</A>
(see Section&nbsp;<A HREF="#mathlib">6.3</A>).
<P>
<H3>4.5.3 - Relational Operators</H3>
The <A NAME="relational operators">relational operators</A> in Lua are
<PRE>
       ==    ~=    &lt;     &gt;     &lt;=    &gt;=
</PRE>
These operators return <B>nil</B> as false and a value different from <B>nil</B> as true.
<P>
Equality (<CODE>==</CODE>) first compares the tags of its operands.
If they are different, then the result is <B>nil</B>.
Otherwise, their values are compared.
Numbers and strings are compared in the usual way.
Tables, userdata, and functions are compared by reference,
that is, two tables are considered equal only if they are the <EM>same</EM> table.
The operator <CODE>~=</CODE> is exactly the negation of equality (<CODE>==</CODE>).
<P>
The conversion rules of Section&nbsp;<A HREF="#coercion">4.2</A>
<EM>do not</EM> apply to equality comparisons.
Thus, <CODE>"0"==0</CODE> evaluates to <EM>false</EM>,
and <CODE>t[0]</CODE> and <CODE>t["0"]</CODE> denote different
entries in a table.
<P>
The order operators work as follows.
If both arguments are numbers, then they are compared as such.
Otherwise, if both arguments are strings,
then their values are compared using lexicographical order.
Otherwise, the ``lt'' tag method is called (see Section&nbsp;<A HREF="#tag-method">4.8</A>).
<P>
<H3>4.5.4 - Logical Operators</H3>
The <A NAME="logical operators">logical operators</A> in Lua are
<A NAME="and"></A><A NAME="or"></A><A NAME="not"></A>
<PRE>
       and   or    not
</PRE>
Like the control structures, all logical operators
consider <B>nil</B> as false and anything else as true.
<P>
The conjunction operator <CODE>and</CODE> returns <B>nil</B> if its first argument is <B>nil</B>;
otherwise, it returns its second argument.
The disjunction operator <CODE>or</CODE> returns its first argument
if it is different from <B>nil</B>;
otherwise, it returns its second argument.
Both <CODE>and</CODE> and <CODE>or</CODE> use <A NAME="short-cut evaluation">short-cut evaluation</A>,
that is,
the second operand is evaluated only if necessary.
<P>
There are two useful Lua idioms that use logical operators.
The first idiom is
<PRE>
       x = x or v
</PRE>
which is equivalent to
<PRE>
       if x == nil then x = v end
</PRE>
This idiom sets <CODE>x</CODE> to a default value <CODE>v</CODE> when <CODE>x</CODE> is not set.
<P>
The second idiom is
<PRE>
       x = a and b or c
</PRE>
which should be read as <CODE>x = (a and b) or c</CODE>.
This idiom is equivalent to
<PRE>
       if a then x = b else x = c end
</PRE>
provided that <CODE>b</CODE> is not <B>nil</B>.
<P>
<A NAME="concat"></A>
<H3>4.5.5 - Concatenation</H3> 
The string <A NAME="concatenation">concatenation</A> operator in Lua is
denoted by two dots (`<A NAME=".."><TT>..</TT></A>').
If both operands are strings or numbers, then they are converted to
strings according to the rules in Section&nbsp;<A HREF="#coercion">4.2</A>.
Otherwise, the ``concat'' tag method is called (see Section&nbsp;<A HREF="#tag-method">4.8</A>).
<P>
<H3>4.5.6 - Precedence</H3>
<A NAME="Operator precedence">Operator precedence</A> in Lua follows the table below,
from the lower to the higher priority:
<PRE>
       and   or
       &lt;     &gt;     &lt;=    &gt;=    ~=    ==
       ..
       +     -
       *     /
       not   - (unary)
       ^
</PRE>
All binary operators are left associative,
except for <CODE>^</CODE> (exponentiation),
which is right associative.
The pre-compiler may rearrange the order of evaluation of
associative operators (such as&nbsp;<CODE>..</CODE> or&nbsp;<CODE>+</CODE>),
as long as these optimizations do not change normal results.
However, these optimizations may change some results
if you define non-associative
tag methods for these operators.
<P>
<A NAME="tableconstructor"></A>
<H3>4.5.7 - Table Constructors</H3> 
Table <A NAME="constructors">constructors</A> are expressions that create tables;
every time a constructor is evaluated, a new table is created.
Constructors can be used to create empty tables,
or to create a table and initialize some of its fields.
The general syntax for constructors is
<PRE>
       tableconstructor ::= `<B>{</B>' fieldlist `<B>}</B>'
       fieldlist ::= lfieldlist | ffieldlist | lfieldlist `<B>;</B>' ffieldlist | ffieldlist `<B>;</B>' lfieldlist
       lfieldlist ::= [lfieldlist1]
       ffieldlist ::= [ffieldlist1]
</PRE>
<P>
The form <EM>lfieldlist1</EM> is used to initialize lists:
<PRE>
       lfieldlist1 ::= exp {`<B>,</B>' exp} [`<B>,</B>']
</PRE>
The expressions in the list are assigned to consecutive numerical indices,
starting with&nbsp;1.
For example,
<PRE>
       a = {"v1", "v2", 34}
</PRE>
is equivalent to
<PRE>
       do
         local temp = {}
         temp[1] = "v1"
         temp[2] = "v2"
         temp[3] = 34
         a = temp
       end
</PRE>
<P>
The form <EM>ffieldlist1</EM> initializes other fields in a table:
<PRE>
       ffieldlist1 ::= ffield {`<B>,</B>' ffield} [`<B>,</B>']
       ffield ::= `<B>[</B>' exp `<B>]</B>' `<B>=</B>' exp | name `<B>=</B>' exp
</PRE>
For example,
<PRE>
       a = {[f(k)] = g(y), x = 1, y = 3, [0] = b+c}
</PRE>
is equivalent to
<PRE>
       do
         local temp = {}
         temp[f(k)] = g(y)
         temp.x = 1    -- or temp["x"] = 1
         temp.y = 3    -- or temp["y"] = 3
         temp[0] = b+c
         a = temp
       end
</PRE>
An expression like <CODE>{x = 1, y = 4}</CODE> is
in fact syntactic sugar for <CODE>{["x"] = 1, ["y"] = 4}</CODE>.
<P>
Both forms may have an optional trailing comma,
and can be used in the same constructor separated by
a semi-colon.
For example, all forms below are correct.
<PRE>
       x = {;}
       x = {"a", "b",}
       x = {type="list"; "a", "b"}
       x = {f(0), f(1), f(2),; n=3,}
</PRE>
<P>
<A NAME="functioncall"></A>
<H3>4.5.8 - Function Calls</H3>  
A <A NAME="function call">function call</A> in Lua has the following syntax:
<PRE>
       functioncall ::= varorfunc args
</PRE>
First, <EM>varorfunc</EM> is evaluated.
If its value has type <EM>function</EM>,
then this function is called,
with the given arguments.
Otherwise, the ``function'' tag method is called,
having as first parameter the value of <EM>varorfunc</EM>,
and then the original call arguments
(see Section&nbsp;<A HREF="#tag-method">4.8</A>).
<P>
The form
<PRE>
       functioncall ::= varorfunc `<B>:</B>' name args
</PRE>
can be used to call ``methods''.
A call <CODE>v:name(...)</CODE>
is syntactic sugar for <CODE>v.name(v, ...)</CODE>,
except that <CODE>v</CODE> is evaluated only once.
<P>
Arguments have the following syntax:
<PRE>
       args ::= `<B>(</B>' [explist1] `<B>)</B>'
       args ::= tableconstructor
       args ::= literal
       explist1 ::= {exp1 `<B>,</B>'} exp
</PRE>
All argument expressions are evaluated before the call.
A call of the form <CODE>f{...}</CODE> is syntactic sugar for
<CODE>f({...})</CODE>, that is,
the argument list is a single new table.
A call of the form <CODE>f'...'</CODE>
(or <CODE>f"..."</CODE> or <CODE>f[[...]]</CODE>) is syntactic sugar for
<CODE>f('...')</CODE>, that is,
the argument list is a single literal string.
<P>
Because a function can return any number of results
(see Section&nbsp;<A HREF="#return">4.4.3</A>),
the number of results must be adjusted before they are used (see Section&nbsp;<A HREF="#adjust">4.3</A>).
If the function is called as a statement (see Section&nbsp;<A HREF="#funcstat">4.4.5</A>),
then its return list is adjusted to&nbsp;0,
thus discarding all returned values.
If the function is called in a place that needs a single value
(syntactically denoted by the non-terminal <EM>exp1</EM>),
then its return list is adjusted to&nbsp;1,
thus discarding all returned values but the first one.
If the function is called in a place that can hold many values
(syntactically denoted by the non-terminal <EM>exp</EM>),
then no adjustment is made.
The only places that can hold many values
is the last (or the only) expression in an assignment,
in an argument list, or in the <B>return</B> statement.
Here are some examples:
<PRE>
       f()                -- adjusted to 0 results
       g(f(), x)          -- f() is adjusted to 1 result
       g(x, f())          -- g gets x plus all values returned by f()
       a,b,c = f(), x     -- f() is adjusted to 1 result (and c gets nil)
       a,b,c = x, f()     -- f() is adjusted to 2
       a,b,c = f()        -- f() is adjusted to 3
       return f()         -- returns all values returned by f()
       return x,y,f()     -- returns a, b, and all values returned by f()
</PRE>
<P>
<A NAME="func-def"></A>
<H3>4.5.9 - <A NAME="Function Definitions</H3>">Function Definitions</H3></A> 
<P>
The syntax for function definition is
<PRE>
       function ::= <B>function</B> `<B>(</B>' [parlist1] `<B>)</B>' block <B>end</B>
       stat ::= <B>function</B> funcname `<B>(</B>' [parlist1] `<B>)</B>' block <B>end</B>
       funcname ::= name | name `<B>.</B>' name | name `<B>:</B>' name
</PRE>
The statement
<PRE>
       function f () ... end
</PRE>
is just syntactic sugar for
<PRE>
       f = function () ... end
</PRE>
and the statement
<PRE>
       function v.f () ... end
</PRE>
is syntactic sugar for
<PRE>
       v.f = function () ... end
</PRE>
<P>
A function definition is an executable expression,
whose value has type <EM>function</EM>.
When Lua pre-compiles a chunk,
all its function bodies are pre-compiled too.
Then, whenever Lua executes the function definition,
its upvalues are fixed (see Section&nbsp;<A HREF="#upvalue">4.6</A>),
and the function is <EM>instantiated</EM> (or <EM>closed</EM>).
This function instance (or <EM>closure</EM>)
is the final value of the expression.
Different instances of the same function
may have different upvalues.
<P>
Parameters act as local variables,
initialized with the argument values:
<PRE>
       parlist1 ::= `<B>...</B>'
       parlist1 ::= name {`<B>,</B>' name} [`<B>,</B>' `<B>...</B>']
</PRE>
<A NAME="vararg"></A>

When a function is called,
the list of <A NAME="arguments">arguments</A> is adjusted to
the length of the list of parameters (see Section&nbsp;<A HREF="#adjust">4.3</A>),
unless the function is a <A NAME="vararg function"><EM>vararg function</EM></A>,
which is
indicated by three dots (`<CODE>...</CODE>') at the end of its parameter list.
A vararg function does not adjust its argument list;
instead, it collects all extra arguments into an implicit parameter,
called <A NAME="arg"><TT>arg</TT></A>.
The value of <CODE>arg</CODE> is a table,
with a field&nbsp;<CODE>n</CODE> whose value is the number of extra arguments,
and the extra arguments at positions 1,&nbsp;2,&nbsp;...,&nbsp;<CODE>n</CODE>.
<P>
As an example, consider the following definitions:
<PRE>
       function f(a, b) end
       function g(a, b, ...) end
       function r() return 1,2,3 end
</PRE>
Then, we have the following mapping from arguments to parameters:
<PRE>
       CALL            PARAMETERS
<P>
       f(3)             a=3, b=nil
       f(3, 4)          a=3, b=4
       f(3, 4, 5)       a=3, b=4
       f(r(), 10)       a=1, b=10
       f(r())           a=1, b=2
<P>
       g(3)             a=3, b=nil, arg={n=0}
       g(3, 4)          a=3, b=4, arg={n=0}
       g(3, 4, 5, 8)    a=3, b=4, arg={5, 8; n=2}
       g(5, r())        a=5, b=1, arg={2, 3; n=2}
</PRE>
<P>
Results are returned using the <B>return</B> statement (see Section&nbsp;<A HREF="#return">4.4.3</A>).
If control reaches the end of a function
without encountering a <B>return</B> statement,
then the function returns with no results.
<P>
The syntax
<PRE>
       funcname ::= name `<B>:</B>' name
</PRE>
is used for defining <A NAME="methods"><EM>methods</EM></A>,
that is, functions that have an implicit extra parameter <A NAME="self"><TT>self</TT></A>.
<P>
The statement
<PRE>
       function v:f (...) ... end
</PRE>
is just syntactic sugar for
<PRE>
       v.f = function (self, ...) ... end
</PRE>
Note that the function gets an extra formal parameter called <CODE>self</CODE>.
<P>
<P>
<A NAME="upvalue"></A>
<A NAME="4.6"></A>
<H2>4.6 - Visibility and Upvalues</H2> 
<A NAME="visibility"></A><A NAME="upvalues"></A>
<P>
A function body may refer to its own local variables
(which include its parameters) and to global variables,
as long as they are not <EM>shadowed</EM> by local
variables with the same name from enclosing functions.
A function <EM>cannot</EM> access a local
variable from an enclosing function,
since such variables may no longer exist when the function is called.
However, a function may access the <EM>value</EM> of a local variable
from an enclosing function, using <EM>upvalues</EM>,
whose syntax is
<PRE>
       upvalue ::= `<B>%</B>' name
</PRE>
<P>
An upvalue is somewhat similar to a variable expression,
but whose value is <EM>frozen</EM> when the function wherein it
appears is instantiated.
The name used in an upvalue may be the name of any variable visible
at the point where the function is defined,
that is,
global variables and local variables
from the <EM>immediately enclosing</EM> function.
Note that when the upvalue is a table,
only the <EM>reference</EM> to that table
(which is the value of the upvalue) is frozen;
the table contents can be changed at will.
Using table values as upvalues is a technique for having
writable but private state attached to functions.
<P>
Here are some examples:
<PRE>
       a,b,c = 1,2,3   -- global variables
       local d
       function f (x)
         local b = {}  -- x and b are local to f; b shadows the global b
         local g = function (a)
           local y     -- a and y are local to g
           p = a       -- OK, access local `a'
           p = c       -- OK, access global `c'
           p = b       -- ERROR: cannot access a variable in outer scope
           p = %b      -- OK, access frozen value of `b' (local to `f')
           %b = 3      -- ERROR: cannot change an upvalue
           %b.x = 3    -- OK, change the table contents
           p = %c      -- OK, access frozen value of global `c'
           p = %y      -- ERROR: `y' is not visible where `g' is defined
           p = %d      -- ERROR: `d' is not visible where `g' is defined
         end           -- g
       end             -- f
</PRE>
<P>
<P>
<A NAME="error"></A>
<A NAME="4.7"></A>
<H2>4.7 - Error Handling</H2> 
<P>
Because Lua is an extension language,
all Lua actions start from C&nbsp;code in the host program
calling a function from the Lua library.
Whenever an error occurs during Lua compilation or execution,
the function <CODE>_ERRORMESSAGE</CODE> is called <A NAME="_ERRORMESSAGE"></A>
(provided it is different from <B>nil</B>),
and then the corresponding function from the library
(<CODE>lua_dofile</CODE>, <CODE>lua_dostring</CODE>,
<CODE>lua_dobuffer</CODE>, or <CODE>lua_call</CODE>)
is terminated, returning an error condition.
<P>
Memory allocation errors are an exception to the previous rule.
When memory allocation fails, Lua may not be able to execute the
<CODE>_ERRORMESSAGE</CODE> function.
So, for this kind of error, Lua does not call
the <CODE>_ERRORMESSAGE</CODE> function;
instead, the corresponding function from the library
returns immediately with a special error code (<CODE>LUA_ERRMEM</CODE>).
This and other error codes are defined in <CODE>lua.h</CODE>;
Section&nbsp;<A HREF="#luado">5.8</A>.
<P>
The only argument to <CODE>_ERRORMESSAGE</CODE> is a string
describing the error.
The default definition for
this function calls <CODE>_ALERT</CODE>, <A NAME="_ALERT"></A>
which prints the message to <CODE>stderr</CODE> (see Section&nbsp;<A HREF="#alert">6.1</A>).
The standard I/O library redefines <CODE>_ERRORMESSAGE</CODE>
and uses the debug facilities (see Section&nbsp;<A HREF="#debugI">7</A>)
to print some extra information,
such as a call stack traceback.
<P>
Lua code can explicitly generate an error by calling the
function <CODE>error</CODE> (see Section&nbsp;<A HREF="#pdf-error">6.1</A>).
Lua code can ``catch'' an error using the function
<CODE>call</CODE> (see Section&nbsp;<A HREF="#pdf-call">6.1</A>).
<P>
<P>
<A NAME="tag-method"></A>
<A NAME="4.8"></A>
<H2>4.8 - Tag Methods</H2> 
<P>
Lua provides a powerful mechanism to extend its semantics,
called <EM>tag methods</EM>.
A tag method is a programmer-defined function
that is called at specific key points during the execution of a Lua program,
allowing the programmer to change the standard Lua behavior at these points.
Each of these points is called an <A NAME="event"><EM>event</EM></A>.
<P>
The tag method called for any specific event is selected
according to the tag of the values involved
in the event (see Section&nbsp;<A HREF="#TypesSec">3</A>).
The function <A NAME="settagmethod"><TT>settagmethod</TT></A> changes the tag method
associated with a given pair <EM>(tag, event)</EM>.
Its first parameter is the tag, the second parameter is the event name
(a string; see below),
and the third parameter is the new method (a function),
or <B>nil</B> to restore the default behavior for the pair.
The <CODE>settagmethod</CODE> function returns the previous tag method for that pair.
A companion function <A NAME="gettagmethod"><TT>gettagmethod</TT></A>
receives a tag and an event name and returns the
current method associated with the pair.
<P>
Tag methods are called in the following events,
identified by the given names.
The semantics of tag methods is better explained by a Lua function
describing the behavior of the interpreter at each event.
This function not only shows when a tag method is called,
but also its arguments, its results, and the default behavior.
The code shown here is only <EM>illustrative</EM>;
the real behavior is hard coded in the interpreter,
and it is much more efficient than this simulation.
All functions used in these descriptions
(<CODE>rawget</CODE>, <CODE>tonumber</CODE>, <CODE>call</CODE>, etc.)
are described in Section&nbsp;<A HREF="#predefined">6.1</A>.
<P>
<DL>
<P>
<DT><B>``add'':</B><DD><A NAME="add event"></A>
called when a <CODE>+</CODE> operation is applied to non-numerical operands.
<P>
The function <CODE>getbinmethod</CODE> below defines how Lua chooses a tag method
for a binary operation.
First, Lua tries the first operand.
If its tag does not define a tag method for the operation,
then Lua tries the second operand.
If it also fails, then it gets a tag method from tag&nbsp;0.
<PRE>
       function getbinmethod (op1, op2, event)
         return gettagmethod(tag(op1), event) or
                gettagmethod(tag(op2), event) or
                gettagmethod(0, event)
       end
</PRE>
Using this function,
the tag method for the ``add'' event is
<PRE>
       function add_event (op1, op2)
         local o1, o2 = tonumber(op1), tonumber(op2)
         if o1 and o2 then  -- both operands are numeric
           return o1+o2  -- '+' here is the primitive 'add'
         else  -- at least one of the operands is not numeric
           local tm = getbinmethod(op1, op2, "add")
           if tm then
             -- call the method with both operands and an extra
             -- argument with the event name
             return tm(op1, op2, "add")
           else  -- no tag method available: default behavior
             error("unexpected type at arithmetic operation")
           end
         end
       end
</PRE>
<P>
<DT><B>``sub'':</B><DD><A NAME="sub event"></A>
called when a <CODE>-</CODE> operation is applied to non-numerical operands.
Behavior similar to the ``add'' event.
<P>
<DT><B>``mul'':</B><DD><A NAME="mul event"></A>
called when a <CODE>*</CODE> operation is applied to non-numerical operands.
Behavior similar to the ``add'' event.
<P>
<DT><B>``div'':</B><DD><A NAME="div event"></A>
called when a <CODE>/</CODE> operation is applied to non-numerical operands.
Behavior similar to the ``add'' event.
<P>
<DT><B>``pow'':</B><DD><A NAME="pow event"></A>
called when a <CODE>^</CODE> operation (exponentiation) is applied,
even for numerical operands.
<PRE>
       function pow_event (op1, op2)
         local tm = getbinmethod(op1, op2, "pow")
         if tm then
           -- call the method with both operands and an extra
           -- argument with the event name
           return tm(op1, op2, "pow")
         else  -- no tag method available: default behavior
           error("unexpected type at arithmetic operation")
         end
       end
</PRE>
<P>
<DT><B>``unm'':</B><DD><A NAME="unm event"></A>
called when a unary <CODE>-</CODE> operation is applied to a non-numerical operand.
<PRE>
       function unm_event (op)
         local o = tonumber(op)
         if o then  -- operand is numeric
           return -o  -- '-' here is the primitive 'unm'
         else  -- the operand is not numeric.
           -- Try to get a tag method from the operand;
           --  if it does not have one, try a "global" one (tag 0)
           local tm = gettagmethod(tag(op), "unm") or
                      gettagmethod(0, "unm")
           if tm then
             -- call the method with the operand, nil, and an extra
             -- argument with the event name
             return tm(op, nil, "unm")
           else  -- no tag method available: default behavior
             error("unexpected type at arithmetic operation")
           end
         end
       end
</PRE>
<P>
<DT><B>``lt'':</B><DD><A NAME="lt event"></A>
called when an order operation is applied to non-numerical
or non-string operands.
It corresponds to the <CODE>&lt;</CODE> operator.
<PRE>
       function lt_event (op1, op2)
         if type(op1) == "number" and type(op2) == "number" then
           return op1 &lt; op2   -- numeric comparison
         elseif type(op1) == "string" and type(op2) == "string" then
           return op1 &lt; op2   -- lexicographic comparison
         else
           local tm = getbinmethod(op1, op2, "lt")
           if tm then
             return tm(op1, op2, "lt")
           else
             error("unexpected type at comparison");
           end
         end
       end
</PRE>
The other order operators use this tag method according to the
usual equivalences:
<PRE>
       a&gt;b    &lt;=&gt;  b&lt;a
       a&lt;=b   &lt;=&gt;  not (b&lt;a)
       a&gt;=b   &lt;=&gt;  not (a&lt;b)
</PRE>
<P>
<DT><B>``concat'':</B><DD><A NAME="concatenation event"></A>
called when a concatenation is applied to non-string operands.
<PRE>
       function concat_event (op1, op2)
         if (type(op1) == "string" or type(op1) == "number") and
            (type(op2) == "string" or type(op2) == "number") then
           return op1..op2  -- primitive string concatenation
         else
           local tm = getbinmethod(op1, op2, "concat")
           if tm then
             return tm(op1, op2, "concat")
           else
             error("unexpected type for concatenation")
           end
         end
       end
</PRE>
<P>
<DT><B>``index'':</B><DD><A NAME="index event"></A>
called when Lua tries to retrieve the value of an index
not present in a table.
See the ``gettable'' event for its semantics.
<P>
<DT><B>``getglobal'':</B><DD><A NAME="getglobal event"></A>
called whenever Lua needs the value of a global variable.
This method can only be set for <B>nil</B> and for tags
created by <CODE>newtag</CODE>.
Note that
the tag is that of the <EM>current value</EM> of the global variable.
<PRE>
       function getglobal (varname)
         -- access the table of globals
         local value = rawget(globals(), varname)
         local tm = gettagmethod(tag(value), "getglobal")
         if not tm then
           return value
         else
           return tm(varname, value)
         end
       end
</PRE>
The function <CODE>getglobal</CODE> is defined in the basic library&nbsp;(see Section&nbsp;<A HREF="#predefined">6.1</A>).
<P>
<DT><B>``setglobal'':</B><DD><A NAME="setglobal event"></A>
called whenever Lua assigns to a global variable.
This method cannot be set for numbers, strings, and tables and
userdata with the default tag.
<PRE>
       function setglobal (varname, newvalue)
         local oldvalue = rawget(globals(), varname)
         local tm = gettagmethod(tag(oldvalue), "setglobal")
         if not tm then
           rawset(globals(), varname, newvalue)
         else
           tm(varname, oldvalue, newvalue)
         end
       end
</PRE>
The function <CODE>setglobal</CODE> is defined in the basic library&nbsp;(see Section&nbsp;<A HREF="#predefined">6.1</A>).
<P>
<DT><B>``gettable'':</B><DD><A NAME="gettable event"></A>
called whenever Lua accesses an indexed variable.
This method cannot be set for tables with the default tag.
<PRE>
       function gettable_event (table, index)
         local tm = gettagmethod(tag(table), "gettable")
         if tm then
           return tm(table, index)
         elseif type(table) ~= "table" then
           error("indexed expression not a table");
         else
           local v = rawget(table, index)
           tm = gettagmethod(tag(table), "index")
           if v == nil and tm then
             return tm(table, index)
           else
             return v
           end
         end
       end
</PRE>
<P>
<DT><B>``settable'':</B><DD><A NAME="settable event"></A>
called when Lua assigns to an indexed variable.
This method cannot be set for tables with the default tag.
<PRE>
       function settable_event (table, index, value)
         local tm = gettagmethod(tag(table), "settable")
         if tm then
           tm(table, index, value)
         elseif type(table) ~= "table" then
           error("indexed expression not a table")
         else
           rawset(table, index, value)
         end
       end
</PRE>
<P>
<DT><B>``function'':</B><DD><A NAME="function event"></A>
called when Lua tries to call a non-function value.
<PRE>
       function function_event (func, ...)
         if type(func) == "function" then
           return call(func, arg)
         else
           local tm = gettagmethod(tag(func), "function")
           if tm then
             for i=arg.n,1,-1 do
               arg[i+1] = arg[i]
             end
             arg.n = arg.n+1
             arg[1] = func
             return call(tm, arg)
           else
             error("call expression not a function")
           end
         end
       end
</PRE>
<P>
<DT><B>``gc'':</B><DD><A NAME="gc event"></A>
called when Lua is ``garbage collecting'' a userdata.
This tag method can be set only from&nbsp;C,
and cannot be set for a userdata with the default tag.
For each userdata to be collected,
Lua does the equivalent of the following function:
<PRE>
       function gc_event (obj)
         local tm = gettagmethod(tag(obj), "gc")
         if tm then
           tm(obj)
         end
       end
</PRE>
In a garbage-collection cycle,
the tag methods for userdata are called in <EM>reverse</EM> order of tag creation,
that is, the first tag methods to be called are those associated
with the last tag created in the program.
Moreover, at the end of the cycle,
Lua does the equivalent of the call <CODE>gc_event(nil)</CODE>.
<P>
</DL>
<P>
<P>
<P>
<P>
<!-- ====================================================================== -->
<HR>
<A NAME="5."></A>
<H1>5 - The Application Program Interface</H1>
<A NAME="C API"></A>
This section describes the API for Lua, that is,
the set of C&nbsp;functions available to the host program to communicate
with Lua.
All API functions and related types and constants
are declared in the header file <CODE>lua.h</CODE>.
<P>
Even when we use the term ``function'',
any facility in the API may be provided as a <EM>macro</EM> instead.
All such macros use each of its arguments exactly once,
and so do not generate hidden side-effects.
<P>
<P>
<A NAME="mangstate"></A>
<A NAME="5.1"></A>
<H2>5.1 - States</H2> 
<P>
The Lua library is fully reentrant:
it does not have any global variables.
<A NAME="state"></A>
The whole state of the Lua interpreter
(global variables, stack, tag methods, etc.)
is stored in a dynamically allocated structure of type <CODE>lua_State</CODE>; <A NAME="lua_State"></A>
this state must be passed as the first argument to
every function in the library (except <CODE>lua_open</CODE> below).
<P>
Before calling any API function,
you must create a state by calling
<A NAME="lua_open"></A>
<PRE>
       lua_State *lua_open (int stacksize);
</PRE>
The sole argument to this function is the stack size for the interpreter.
(Each function call needs one stack position for each argument, local variable,
and temporary value, plus one position for book-keeping.
The stack must also have some 20 extra positions available.
For very small implementations, without recursive functions,
a stack size of&nbsp;100 should be enough.)
If <CODE>stacksize</CODE> is zero,
then a default size of&nbsp;1024 is used.
<P>
To release a state created with <CODE>lua_open</CODE>, call
<A NAME="lua_close"></A>
<PRE>
       void lua_close (lua_State *L);
</PRE>
This function destroys all objects in the given Lua environment
(calling the corresponding garbage-collection tag methods, if any)
and frees all dynamic memory used by that state.
Usually, you do not need to call this function,
because all resources are naturally released when your program ends.
On the other hand,
long-running programs -
like a daemon or a web server -
might need to release states as soon as they are not needed,
to avoid growing too big.
<P>
With the exception of <CODE>lua_open</CODE>,
all functions in the Lua API need a state as their first argument.
<P>
<P>
<A NAME="5.2"></A>
<H2>5.2 - The Stack and Indices</H2>
<P>
Lua uses a <EM>stack</EM> to pass values to and from C.
Each element in this stack represents a Lua value
(nil, number, string, etc.).
<P>
For convenience,
most query operations in the API do not follow a strict stack discipline.
Instead, they can refer to any element in the stack by using an <EM>index</EM>:
A positive index represents an <EM>absolute</EM> stack position
(starting at&nbsp;1, not 0 as in C);
a negative index represents an <EM>offset</EM> from the top of the stack.
More specifically, if the stack has <EM>n</EM> elements,
index&nbsp;1 represents the first element
(that is, the first element pushed onto the stack),
and
index&nbsp;<EM>n</EM> represents the last element;
index&nbsp;<I>-1</I> also represents the last element
(that is, the element at the top),
and index <I>-n</I> represents the first element.
We say that an index is <EM>valid</EM>
if it lays between&nbsp;1 and the stack top
(that is, if <CODE>1 &lt;= abs(index) &lt;= top</CODE>).
<A NAME="stack index"></A> <A NAME="valid index"></A>
<P>
At any time, you can get the index of the top element by calling
<A NAME="lua_gettop"></A>
<PRE>
       int lua_gettop (lua_State *L);
</PRE>
Because indices start at&nbsp;1,
the result of <CODE>lua_gettop</CODE> is equal to the number of elements in the stack
(and so 0&nbsp;means an empty stack).
<P>
When you interact with Lua API,
<EM>you are responsible for controlling stack overflow</EM>.
The function <A NAME="lua_stackspace"></A>
<PRE>
       int lua_stackspace (lua_State *L);
</PRE>
returns the number of stack positions still available.
Whenever Lua calls C, <A NAME="LUA_MINSTACK"></A>
it ensures that
at least <CODE>LUA_MINSTACK</CODE> positions are still available.
<CODE>LUA_MINSTACK</CODE> is defined in <CODE>lua.h</CODE> and is at least&nbsp;16,
and so you have to worry about stack space only
when your code has loops pushing elements onto the stack.
<P>
Most query functions accept as indices any value inside the
available stack space.
Such indices are called <EM>acceptable indices</EM>.
More formally, we can define an <A NAME="acceptable index"><EM>acceptable index</EM></A>
as
<PRE>
     (index &lt; 0 &amp;&amp; abs(index) &lt;= top) || (index &gt; 0 &amp;&amp; index &lt;= top + stackspace)
</PRE>
Note that 0 is not an acceptable index.
<P>
<A NAME="5.3"></A>
<H2>5.3 - Stack Manipulation</H2>
The API offers the following functions for basic stack manipulation:
<A NAME="lua_settop"></A><A NAME="lua_pushvalue"></A>
<A NAME="lua_remove"></A><A NAME="lua_insert"></A>
<PRE>
       void lua_settop    (lua_State *L, int index);
       void lua_pushvalue (lua_State *L, int index);
       void lua_remove    (lua_State *L, int index);
       void lua_insert    (lua_State *L, int index);
</PRE>
<P>
<CODE>lua_settop</CODE> accepts any acceptable index,
or 0,
and sets the stack top to that index.
If the new top is larger than the old one,
then the new elements are filled with <B>nil</B>.
If <CODE>index</CODE> is 0, then all stack elements are removed.
A useful macro defined in the API is
<PRE>
       #define lua_pop(L,n) lua_settop(L, -(n)-1)
</PRE>
which pops <CODE>n</CODE> elements from the stack.
<P>
<CODE>lua_pushvalue</CODE> pushes onto the stack a <EM>copy</EM> of the element
at the given index.
<CODE>lua_remove</CODE> removes the element at the given position,
shifting down the elements on top of that position to fill in the gap.
<CODE>lua_insert</CODE> moves the top element into the given position,
shifting up the elements on top of that position to open space.
These functions accept only valid indices.
As an example, if the stack starts as <CODE>10 20 30 40 50</CODE>
(from bottom to top),
then
<PRE>
       lua_pushvalue(L, 3)    --&gt; 10 20 30 40 50 30
       lua_pushvalue(L, -1)   --&gt; 10 20 30 40 50 30 30
       lua_remove(L, -3)      --&gt; 10 20 30 40 30 30
       lua_remove(L,  6)      --&gt; 10 20 30 40 30
       lua_insert(L,  1)      --&gt; 30 10 20 30 40
       lua_insert(L, -1)      --&gt; 30 10 20 30 40  (no effect)
       lua_settop(L, -3)      --&gt; 30 10 20
       lua_settop(L, 6)       --&gt; 30 10 20 nil nil nil
</PRE>
<P>
<P>
<A NAME="5.4"></A>
<H2>5.4 - Querying the Stack</H2>
<P>
To check the type of a stack element,
the following functions are available:
<A NAME="lua_type"></A><A NAME="lua_tag"></A>
<A NAME="lua_isnil"></A><A NAME="lua_isnumber"></A><A NAME="lua_isstring"></A>
<A NAME="lua_istable"></A>
<A NAME="lua_isfunction"></A><A NAME="lua_iscfunction"></A><A NAME="lua_isuserdata"></A>
<PRE>
       int         lua_type        (lua_State *L, int index);
       int         lua_tag         (lua_State *L, int index);
       int         lua_isnil       (lua_State *L, int index);
       int         lua_isnumber    (lua_State *L, int index);
       int         lua_isstring    (lua_State *L, int index);
       int         lua_istable     (lua_State *L, int index);
       int         lua_isfunction  (lua_State *L, int index);
       int         lua_iscfunction (lua_State *L, int index);
       int         lua_isuserdata  (lua_State *L, int index);
</PRE>
These functions can be called with any acceptable index.
<P>
<CODE>lua_type</CODE> returns one of the following constants,
according to the type of the given object:
<CODE>LUA_TNIL</CODE>,
<CODE>LUA_TNUMBER</CODE>,
<CODE>LUA_TSTRING</CODE>,
<CODE>LUA_TTABLE</CODE>,
<CODE>LUA_TFUNCTION</CODE>,
<CODE>LUA_TUSERDATA</CODE>.
If the index is non-valid
(that is, if that stack position is ``empty''),
then <CODE>lua_type</CODE> returns <CODE>LUA_TNONE</CODE>.
These constants can be converted to strings with
<A NAME="lua_typename"></A>
<PRE>
       const char *lua_typename (lua_State *L, int t);
</PRE>
where <CODE>t</CODE> is a type returned by <CODE>lua_type</CODE>.
The strings returned by <CODE>lua_typename</CODE> are
<CODE>"nil"</CODE>, <CODE>"number"</CODE>, <CODE>"string"</CODE>, <CODE>"table"</CODE>,
<CODE>"function"</CODE>, <CODE>"userdata"</CODE>, and <CODE>"no value"</CODE>,
<P>
<CODE>lua_tag</CODE> returns the tag of a value,
or <CODE>LUA_NOTAG</CODE> for a non-valid index.
<P>
The <CODE>lua_is*</CODE> functions return&nbsp;1 if the object is compatible
with the given type, and 0 otherwise.
They always return 0 for a non-valid index.
<CODE>lua_isnumber</CODE> accepts numbers and numerical strings,
<CODE>lua_isstring</CODE> accepts strings and numbers (see Section&nbsp;<A HREF="#coercion">4.2</A>),
and <CODE>lua_isfunction</CODE> accepts both Lua functions and C&nbsp;functions.
To distinguish between Lua functions and C&nbsp;functions,
you should use <CODE>lua_iscfunction</CODE>.
To distinguish between numbers and numerical strings,
you can use <CODE>lua_type</CODE>.
<P>
The API also has functions to compare two values in the stack:
<A NAME="lua_equal"></A>
<A NAME="lua_lessthan"></A>
<PRE>
       int lua_equal    (lua_State *L, int index1, int index2);
       int lua_lessthan (lua_State *L, int index1, int index2);
</PRE>
These functions are equivalent to their counterparts in Lua.
Specifically, <CODE>lua_lessthan</CODE> is equivalent to the <CODE>lt_event</CODE>
described in Section&nbsp;<A HREF="#tag-method">4.8</A>.
Both functions return 0 if any of the indices are non-valid.
<P>
To translate a value in the stack to a specific C&nbsp;type,
you can use the following conversion functions:
<A NAME="lua_tonumber"></A><A NAME="lua_tostring"></A><A NAME="lua_strlen"></A>
<A NAME="lua_tocfunction"></A><A NAME="lua_touserdata"></A>
<PRE>
       double         lua_tonumber    (lua_State *L, int index);
       const char    *lua_tostring    (lua_State *L, int index);
       size_t         lua_strlen      (lua_State *L, int index);
       lua_CFunction  lua_tocfunction (lua_State *L, int index);
       void          *lua_touserdata  (lua_State *L, int index);
</PRE>
These functions can be called with any acceptable index.
When called with a non-valid index,
they act as if the given value had an incorrect type.
<P>
<CODE>lua_tonumber</CODE> converts the value at the given index
to a floating-point number.
This value must be a number or a string convertible to number
(see Section&nbsp;<A HREF="#coercion">4.2</A>); otherwise, <CODE>lua_tonumber</CODE> returns&nbsp;0.
<P>
<CODE>lua_tostring</CODE> converts a Lua value to a string
(<CODE>const char*</CODE>).
This value must be a string or a number;
otherwise, the function returns <CODE>NULL</CODE>.
This function returns a pointer to a string inside the Lua environment.
Those strings always have a zero (<CODE>'\0'</CODE>) after their last character (as in C),
but may contain other zeros in their body.
If you do not know whether a string may contain zeros,
you should use <CODE>lua_strlen</CODE> to get its actual length.
Because Lua has garbage collection,
there is no guarantee that the pointer returned by <CODE>lua_tostring</CODE>
will be valid after the respective value is removed from the stack.
<P>
<CODE>lua_tocfunction</CODE> converts a value in the stack to a C&nbsp;function.
This value must be a C&nbsp;function;
otherwise, <CODE>lua_tocfunction</CODE> returns <CODE>NULL</CODE>.
The type <CODE>lua_CFunction</CODE> is explained in Section&nbsp;<A HREF="#LuacallC">5.13</A>.
<P>
<CODE>lua_touserdata</CODE> converts a value to <CODE>void*</CODE>.
This value must have type <EM>userdata</EM>;
otherwise, <CODE>lua_touserdata</CODE> returns <CODE>NULL</CODE>.
<P>
<P>
<P>
<A NAME="5.5"></A>
<H2>5.5 - Pushing values onto the Stack</H2>
<P>
The API has the following functions to
push C&nbsp;values onto the stack:
<A NAME="lua_pushnumber"></A><A NAME="lua_pushlstring"></A><A NAME="lua_pushstring"></A>
<A NAME="lua_pushcfunction"></A><A NAME="lua_pushusertag"></A>
<A NAME="pushing"></A>
<A NAME="lua_pushnil"></A><A NAME="lua_pushuserdata"></A>
<PRE>
       void lua_pushnumber    (lua_State *L, double n);
       void lua_pushlstring   (lua_State *L, const char *s, size_t len);
       void lua_pushstring    (lua_State *L, const char *s);
       void lua_pushusertag   (lua_State *L, void *u, int tag);
       void lua_pushnil       (lua_State *L);
       void lua_pushcfunction (lua_State *L, lua_CFunction f);
</PRE>
These functions receive a C&nbsp;value,
convert it to a corresponding Lua value,
and push the result onto the stack.
In particular, <CODE>lua_pushlstring</CODE> and <CODE>lua_pushstring</CODE>
make an <EM>internal copy</EM> of the given string.
<CODE>lua_pushstring</CODE> can only be used to push proper C&nbsp;strings
(that is, strings that end with a zero and do not contain embedded zeros);
otherwise you should use the more general <CODE>lua_pushlstring</CODE>,
which accepts an explicit size.
<P>
<P>
<A NAME="GC"></A>
<A NAME="5.6"></A>
<H2>5.6 - Garbage Collection</H2>
<P>
Lua uses two numbers to control its garbage collection.
One number counts how many bytes of dynamic memory Lua is using,
and the other is a threshold.
(This internal byte counter kept by Lua is not completely acurate;
it is just a lower bound, usually within&nbsp;10% of the correct value.)
When the number of bytes crosses the threshold,
Lua runs a garbage-collection cycle,
which reclaims the memory of all ``dead'' objects
(that is, objects no longer accessible from Lua).
The byte counter is corrected,
and then the threshold is reset to twice the value of the byte counter.
<P>
You can access the current values of these two numbers through the
following functions:
<A NAME="lua_getgcthreshold"></A> <A NAME="lua_getgccount"></A>
<PRE>
       int  lua_getgccount (lua_State *L);
       int  lua_getgcthreshold (lua_State *L);
</PRE>
Both return their respective values in Kbytes.
You can change the threshold value with
<A NAME="lua_setgcthreshold"></A>
<PRE>
       void  lua_setgcthreshold (lua_State *L, int newthreshold);
</PRE>
Again, the <CODE>newthreshold</CODE> value is given in Kbytes.
When you call this function,
Lua sets the new threshold and checks it against the byte counter.
If the new threshold is smaller than the byte counter,
then Lua immediately runs the garbage collector;
after the collection, 
a new threshold is set according to the previous rule.
<P>
If you want to change the adaptative behavior of the garbage collector,
you can use the garbage-collection tag method for <B>nil</B> 
to set your own threshold
(the tag method is called after Lua resets the threshold).
<P>
<P>
<A NAME="C-tags"></A>
<A NAME="5.7"></A>
<H2>5.7 - Userdata and Tags</H2>
<P>
Because userdata are objects,
the function <CODE>lua_pushusertag</CODE> may create a new userdata.
If Lua has a userdata with the given value (<CODE>void*</CODE>) and tag,
then that userdata is pushed.
Otherwise, a new userdata is created, with the given value and tag.
If this function is called with
<CODE>tag</CODE> equal to <CODE>LUA_ANYTAG</CODE><A NAME="LUA_ANYTAG"></A>,
then Lua will try to find any userdata with the given value,
regardless of its tag.
If there is no userdata with that value, then a new one is created,
with tag equal to 0.
<P>
Userdata can have different tags,
whose semantics are only known to the host program.
Tags are created with the function
<A NAME="lua_newtag"></A>
<PRE>
       int lua_newtag (lua_State *L);
</PRE>
The function <CODE>lua_settag</CODE> changes the tag of
the object on top of the stack (without popping it):
<A NAME="lua_settag"></A>
<PRE>
       void lua_settag (lua_State *L, int tag);
</PRE>
The object must be a userdata or a table;
the given <CODE>tag</CODE> must be a value created with <CODE>lua_newtag</CODE>.
<P>
<A NAME="luado"></A>
<A NAME="5.8"></A>
<H2>5.8 - Executing Lua Code</H2>
A host program can execute Lua chunks written in a file or in a string
by using the following functions:
<A NAME="lua_dofile"></A><A NAME="lua_dostring"></A><A NAME="lua_dobuffer"></A>
<PRE>
       int lua_dofile   (lua_State *L, const char *filename);
       int lua_dostring (lua_State *L, const char *string);
       int lua_dobuffer (lua_State *L, const char *buff,
                         size_t size, const char *name);
</PRE>
These functions return
0 in case of success, or one of the following error codes if they fail:
<UL>
<LI><A NAME="LUA_ERRRUN"><TT>LUA_ERRRUN</TT></A> -
error while running the chunk.
<LI><A NAME="LUA_ERRSYNTAX"><TT>LUA_ERRSYNTAX</TT></A> -
syntax error during pre-compilation.
<LI><A NAME="LUA_ERRMEM"><TT>LUA_ERRMEM</TT></A> -
memory allocation error.
For such errors, Lua does not call <CODE>_ERRORMESSAGE</CODE> (see Section&nbsp;<A HREF="#error">4.7</A>).
<LI><A NAME="LUA_ERRERR"><TT>LUA_ERRERR</TT></A> -
error while running <CODE>_ERRORMESSAGE</CODE>.
For such errors, Lua does not call <CODE>_ERRORMESSAGE</CODE> again, to avoid loops.
<LI><A NAME="LUA_ERRFILE"><TT>LUA_ERRFILE</TT></A> -
error opening the file (only for <CODE>lua_dofile</CODE>).
In this case,
you may want to
check <CODE>errno</CODE>,
call <CODE>strerror</CODE>,
or call <CODE>perror</CODE> to tell the user what went wrong.
</UL>
These constants are defined in <CODE>lua.h</CODE>.
<P>
When called with argument <CODE>NULL</CODE>,
<CODE>lua_dofile</CODE> executes the <CODE>stdin</CODE> stream.
<CODE>lua_dofile</CODE> and <CODE>lua_dobuffer</CODE>
are both able to execute pre-compiled chunks.
They automatically detect whether the chunk is text or binary,
and load it accordingly (see program <A NAME="luac"><TT><A HREF="luac.html">luac</A></TT></A>).
<CODE>lua_dostring</CODE> executes only source code,
given in textual form.
<P>
The third parameter to <CODE>lua_dobuffer</CODE>
is the ``name of the chunk'',
which is used in error messages and debug information.
If <CODE>name</CODE> is <CODE>NULL</CODE>,
then Lua gives a default name to the chunk.
<P>
These functions push onto the stack
any values eventually returned by the chunk.
A chunk may return any number of values;
Lua takes care that these values fit into the stack space,
but after the call the responsibility is back to you.
If you need to push other elements after calling any of these functions,
and you want to ``play safe'',
you must either check the stack space
with <CODE>lua_stackspace</CODE>
or remove the returned elements
from the stack (if you do not need them).
For instance, the following code
loads a chunk in a file and discards all results returned by this chunk,
leaving the stack as it was before the call:
<PRE>
      {
       int oldtop = lua_gettop(L);
       lua_dofile(L, filename);
       lua_settop(L, oldtop);
      }
</PRE>
<P>
<P>
<A NAME="5.9"></A>
<H2>5.9 - Manipulating Global Variables in Lua</H2>
<P>
To read the value of a global Lua variable,
you call
<A NAME="lua_getglobal"></A>
<PRE>
       void lua_getglobal (lua_State *L, const char *varname);
</PRE>
which pushes onto the stack the value of the given variable.
As in Lua, this function may trigger a tag method
for the ``getglobal'' event (see Section&nbsp;<A HREF="#tag-method">4.8</A>).
To read the real value of a global variable,
without invoking any tag method,
use <CODE>lua_rawget</CODE> over the table of globals
(see below).
<P>
To store a value in a global variable,
you call
<A NAME="lua_setglobal"></A>
<PRE>
       void lua_setglobal (lua_State *L, const char *varname);
</PRE>
which pops from the stack the value to be stored in the given variable.
As in Lua, this function may trigger a tag method
for the ``setglobal'' event (see Section&nbsp;<A HREF="#tag-method">4.8</A>).
To set the real value of a global variable,
without invoking any tag method,
use <CODE>lua_rawset</CODE> over the table of globals
(see below).
<P>
All global variables are kept in an ordinary Lua table.
You can get this table calling
<A NAME="lua_getglobals"></A>
<PRE>
       void lua_getglobals (lua_State *L);
</PRE>
which pushes the current table of globals onto the stack.
To set another table as the table of globals,
you call
<A NAME="lua_setglobals"></A>
<PRE>
       void lua_setglobals (lua_State *L);
</PRE>
The table to be used is popped from the stack.
<P>
<A NAME="5.10"></A>
<H2>5.10 - Manipulating Tables in Lua</H2>
Lua tables can also be manipulated through the API.
<P>
To read the value of in a table,
the table must reside somewhere in the stack.
With this set,
you call
<A NAME="lua_gettable"></A>
<PRE>
       void lua_gettable (lua_State *L, int index);
</PRE>
where <CODE>index</CODE> refers to the table.
<CODE>lua_gettable</CODE> pops a key from the stack,
and returns (on the stack) the contents of the table at that key.
As in Lua, this operation may trigger a tag method
for the ``gettable'' event.
To get the real value of any table key,
without invoking any tag method,
use the <EM>raw</EM> version:
<A NAME="lua_rawget"></A>
<PRE>
       void lua_rawget (lua_State *L, int index);
</PRE>
<P>
To store a value into a table that resides somewhere in the stack,
you push the key and the value onto the stack
(in this order),
and then call
<A NAME="lua_settable"></A>
<PRE>
       void lua_settable (lua_State *L, int index);
</PRE>
where <CODE>index</CODE> refers to the table.
<CODE>lua_settable</CODE> pops from the stack both the key and the value.
As in Lua, this operation may trigger a tag method
for the ``settable'' event.
To set the real value of any table index,
without invoking any tag method,
use the <EM>raw</EM> version:
<A NAME="lua_rawset"></A>
<PRE>
       void lua_rawset (lua_State *L, int index);
</PRE>
<P>
Finally, the function
<A NAME="lua_newtable"></A>
<PRE>
       void lua_newtable (lua_State *L);
</PRE>
creates a new, empty table and pushes it onto the stack.
<P>
<A NAME="5.11"></A>
<H2>5.11 - Using Tables as Arrays</H2>
The API has functions that help to use Lua tables as arrays,
that is,
tables indexed by numbers only:
<A NAME="lua_rawgeti"></A>
<A NAME="lua_rawseti"></A>
<A NAME="lua_getn"></A>
<PRE>
       void lua_rawgeti (lua_State *L, int index, int n);
       void lua_rawseti (lua_State *L, int index, int n);
       int  lua_getn    (lua_State *L, int index);
</PRE>
<P>
<CODE>lua_rawgeti</CODE> gets the value of the <EM>n</EM>-th element of the table
at stack position <CODE>index</CODE>.
<P>
<CODE>lua_rawseti</CODE> sets the value of the <EM>n</EM>-th element of the table
at stack position <CODE>index</CODE> to the value at the top of the stack.
<P>
<CODE>lua_getn</CODE> returns the number of elements in the table
at stack position <CODE>index</CODE>.
This number is the value of the table field <CODE>n</CODE>,
if it has a numeric value,
or
the largest numerical index with a non-nil value in the table.
<P>
<A NAME="5.12"></A>
<H2>5.12 - Calling Lua Functions</H2>
<P>
Functions defined in Lua
(and C&nbsp;functions registered in Lua)
can be called from the host program.
This is done using the following protocol:
First, the function to be called is pushed onto the stack;
then, the arguments to the function are pushed
(see Section&nbsp;<A HREF="#pushing">5.5</A>) in <EM>direct order</EM>, that is, the first argument is pushed first.
Finally, the function is called using
<A NAME="lua_call"></A>
<PRE>
       int lua_call (lua_State *L, int nargs, int nresults);
</PRE>
This function returns the same error codes as <CODE>lua_dostring</CODE> and
friends (see Section&nbsp;<A HREF="#luado">5.8</A>).
If you want to propagate the error,
instead of returning an error code,
use
<A NAME="lua_rawcall"></A>
<PRE>
       void lua_rawcall (lua_State *L, int nargs, int nresults);
</PRE>
<P>
In both functions,
<CODE>nargs</CODE> is the number of arguments that you pushed onto the stack.
All arguments and the function value are popped from the stack,
and the function results are pushed.
The number of results are adjusted (see Section&nbsp;<A HREF="#adjust">4.3</A>) to <CODE>nresults</CODE>,
unless <CODE>nresults</CODE> is <A NAME="LUA_MULTRET"><TT>LUA_MULTRET</TT></A>.
In that case, <EM>all</EM> results from the function are pushed.
The function results are pushed in direct order
(the first result is pushed first),
so that after the call the last result is on the top.
<P>
The following example shows how the host program may do the
equivalent to the Lua code:
<PRE>
       a,b = f("how", t.x, 4)
</PRE>
Here it is in&nbsp;C:
<PRE>
    lua_getglobal(L, "t");                      /* global `t' (for later use) */
    lua_getglobal(L, "f");                           /* function to be called */
    lua_pushstring(L, "how");                                 /* 1st argument */
    lua_pushstring(L, "x");                            /* push the string `x' */
    lua_gettable(L, -4);                      /* push result of t.x (2nd arg) */
    lua_pushnumber(L, 4);                                     /* 3rd argument */
    lua_call(L, 3, 2);        /* call function with 3 arguments and 2 results */
    lua_setglobal(L, "b");                         /* set global variable `b' */
    lua_setglobal(L, "a");                         /* set global variable `a' */
    lua_pop(L, 1);                               /* remove `t' from the stack */
</PRE>
Notice that the code above is ``balanced'':
at its end ,the stack is back to its original configuration.
This is considered good programming practice.
<P>
<P>
<P>
Some special Lua functions have their own C&nbsp;interfaces.
The host program can generate a Lua error calling the function
<A NAME="lua_error"></A>
<PRE>
       void lua_error (lua_State *L, const char *message);
</PRE>
This function never returns.
If <CODE>lua_error</CODE> is called from a C&nbsp;function that has been called from Lua,
then the corresponding Lua execution terminates,
as if an error had occurred inside Lua code.
Otherwise, the whole host program terminates with a call to
<CODE>exit(EXIT_FAILURE)</CODE>.
Before terminating execution,
the <CODE>message</CODE> is passed to the error handler function,
<CODE>_ERRORMESSAGE</CODE> (see Section&nbsp;<A HREF="#error">4.7</A>).
If <CODE>message</CODE> is <CODE>NULL</CODE>,
then <CODE>_ERRORMESSAGE</CODE> is not called.
<P>
<P>
Tag methods can be changed with <A NAME="lua_settagmethod"></A>
<PRE>
       void lua_settagmethod (lua_State *L, int tag, const char *event);
</PRE>
The second parameter is the tag,
and the third is the event name (see Section&nbsp;<A HREF="#tag-method">4.8</A>);
the new method is popped from the stack.
To get the current value of a tag method,
use the function <A NAME="lua_gettagmethod"></A>
<PRE>
       void lua_gettagmethod (lua_State *L, int tag, const char *event);
</PRE>
<P>
It is also possible to copy all tag methods from one tag
to another: <A NAME="lua_copytagmethods"></A>
<PRE>
       int lua_copytagmethods (lua_State *L, int tagto, int tagfrom);
</PRE>
This function returns <CODE>tagto</CODE>.
<P>
<P>
You can traverse a table with the function <A NAME="lua_next"></A>
<PRE>
       int lua_next (lua_State *L, int index);
</PRE>
where <CODE>index</CODE> refers to the table to be traversed.
The function pops a key from the stack,
and pushes a key-value pair from the table
(the ``next'' pair after the given key).
If there are no more elements, then the function returns 0
(and pushes nothing).
A typical traversal looks like this:
<PRE>
       /* table is in the stack at index `t' */
       lua_pushnil(L);  /* first key */
       while (lua_next(L, t) != 0) {
         /* `key' is at index -2 and `value' at index -1 */
         printf("%s - %s\n",
           lua_typename(L, lua_type(L, -2)), lua_typename(L, lua_type(L, -1)));
         lua_pop(L, 1);  /* removes `value'; keeps `index' for next iteration */
       }
</PRE>
<P>
The function <A NAME="lua_concat"></A>
<PRE>
       void lua_concat (lua_State *L, int n);
</PRE>
concatenates the <CODE>n</CODE> values at the top of the stack,
pops them, and leaves the result at the top;
<CODE>n</CODE>&nbsp;must be at least 2.
Concatenation is done following the usual semantics of Lua
(see Section&nbsp;<A HREF="#concat">4.5.5</A>).
<P>
<P>
<A NAME="LuacallC"></A>
<A NAME="5.13"></A>
<H2>5.13 - Defining C Functions</H2> 
To register a C&nbsp;function to Lua,
there is the following convenience macro:
<A NAME="lua_register"></A>
<PRE>
     #define lua_register(L, n, f) (lua_pushcfunction(L, f), lua_setglobal(L, n))
     /* const char *n;   */
     /* lua_CFunction f; */
</PRE>
which receives the name the function will have in Lua,
and a pointer to the function.
This pointer must have type <CODE>lua_CFunction</CODE>,
which is defined as
<A NAME="lua_CFunction"></A>
<PRE>
       typedef int (*lua_CFunction) (lua_State *L);
</PRE>
that is, a pointer to a function with integer result and a single argument,
a Lua environment.
<P>
In order to communicate properly with Lua,
a C&nbsp;function must follow the following protocol,
which defines the way parameters and results are passed:
A C&nbsp;function receives its arguments from Lua in the stack,
in direct order (the first argument is pushed first).
To return values to Lua, a C&nbsp;function just pushes them onto the stack,
in direct order (the first result is pushed first),
and returns the number of results.
Like a Lua function, a C&nbsp;function called by Lua can also return
many results.
<P>
As an example, the following function receives a variable number
of numerical arguments and returns their average and sum:
<PRE>
       static int foo (lua_State *L) {
         int n = lua_gettop(L);    /* number of arguments */
         double sum = 0;
         int i;
         for (i = 1; i &lt;= n; i++) {
           if (!lua_isnumber(L, i))
             lua_error(L, "incorrect argument to function `average'");
           sum += lua_tonumber(L, i);
         }
         lua_pushnumber(L, sum/n);        /* first result */
         lua_pushnumber(L, sum);         /* second result */
         return 2;                   /* number of results */
       }
</PRE>
This function may be registered in Lua as `<CODE>average</CODE>' by calling
<PRE>
       lua_register(L, "average", foo);
</PRE>
<P>
<P>
When a C&nbsp;function is created,
it is possible to associate some <EM>upvalues</EM> to it
(see Section&nbsp;<A HREF="#upvalue">4.6</A>),
thus creating a <A NAME="C closure"><EM>C&nbsp;closure</EM></A>;
these values are passed to the function whenever it is called,
as ordinary arguments.
To associate upvalues to a C&nbsp;function,
first these values should be pushed onto the stack.
Then the function <A NAME="lua_pushcclosure"></A>
<PRE>
       void lua_pushcclosure (lua_State *L, lua_CFunction fn, int n);
</PRE>
is used to push the C&nbsp;function onto the stack,
with the argument <CODE>n</CODE> telling how many upvalues should be
associated with the function
(these upvalues are popped from the stack);
in fact, the macro <CODE>lua_pushcfunction</CODE> is defined as
<CODE>lua_pushcclosure</CODE> with <CODE>n</CODE> set to 0.
Then, whenever the C&nbsp;function is called,
these upvalues are inserted as the <EM>last</EM> arguments to the function,
after the actual arguments provided in the call.
This makes it easy to get the upvalues without knowing how many arguments
the function received (recall that functions in Lua can receive any number of
arguments): The <EM>i</EM>-th upvalue is in the stack at index <I>i-(n+1)</I>,
where <EM>n</EM> is the number of upvalues.
<P>
For more examples of C&nbsp;functions and closures, see files
<CODE>lbaselib.c</CODE>, <CODE>liolib.c</CODE>, <CODE>lmathlib.c</CODE>, and <CODE>lstrlib.c</CODE>
in the official Lua distribution.
<P>
<A NAME="5.14"></A>
<H2>5.14 - References to Lua Objects</H2>
<P>
If the C&nbsp;code needs to keep a Lua value
outside the life span of a C&nbsp;function,
then it must create a <A NAME="reference"><EM>reference</EM></A> to the value.
The functions to manipulate references are the following:
<A NAME="lua_ref"></A><A NAME="lua_getref"></A>
<A NAME="lua_unref"></A>
<PRE>
       int   lua_ref    (lua_State *L, int lock);
       int   lua_getref (lua_State *L, int ref);
       void  lua_unref  (lua_State *L, int ref);
</PRE>
<P>
<CODE>lua_ref</CODE> pops a value from
the stack, creates a reference to it,
and returns this reference.
For a <B>nil</B> value,
the reference is always <CODE>LUA_REFNIL</CODE>.<A NAME="LUA_REFNIL"></A>
(<CODE>lua.h</CODE> also defines a constant <CODE>LUA_NOREF</CODE> <A NAME="LUA_NOREF"></A>
that
is different from any valid reference.)
If <CODE>lock</CODE> is not zero, then the object is <EM>locked</EM>:
this means the object will not be garbage collected.
<EM>Unlocked references may be garbage collected</EM>.
<P>
Whenever the referenced object is needed in&nbsp;C,
a call to <CODE>lua_getref</CODE>
pushes that object onto the stack;
if the object has been collected,
<CODE>lua_getref</CODE> returns 0 (and does not push anything).
<P>
When a reference is no longer needed,
it should be released with a call to <CODE>lua_unref</CODE>.
<P>
<P>
<h3>Registry</h3>
<P>
When Lua starts, it registers a table at position
<A NAME="LUA_REFREGISTRY"><TT>LUA_REFREGISTRY</TT></A>.
It can be accessed through the macro<A NAME="lua_getregistry"></A>
<PRE>
  #define lua_getregistry(L)      lua_getref(L, LUA_REFREGISTRY)
</PRE>
This table can be used by C&nbsp;libraries as a general registry mechanism.
Any C&nbsp;library can store data into this table,
as long as it chooses a key different from other libraries.
<P>
<P>
<!-- ====================================================================== -->
<HR>
<A NAME="6."></A>
<H1>6 - Standard Libraries</H1>
<P>
The standard libraries provide useful functions
that are implemented directly through the standard API.
Therefore, they are not necessary to the language,
and are provided as separate C&nbsp;modules.
Currently, Lua has the following standard libraries:
<UL>
<LI>basic library;
<LI>string manipulation;
<LI>mathematical functions (sin, log, etc);
<LI>input and output (plus some system facilities).
</UL>
To have access to these libraries,
the C&nbsp;host program must call the functions
<CODE>lua_baselibopen</CODE>,
<CODE>lua_strlibopen</CODE>, <CODE>lua_mathlibopen</CODE>,
and <CODE>lua_iolibopen</CODE>, which are declared in <CODE>lualib.h</CODE>.
<A NAME="lua_baselibopen"></A>
<A NAME="lua_strlibopen"></A>
<A NAME="lua_mathlibopen"></A>
<A NAME="lua_iolibopen"></A>
<P>
<A NAME="predefined"></A>
<A NAME="6.1"></A>
<H2>6.1 - Basic Functions</H2> 
<P>
The basic library provides some core functions to Lua.
Therefore, if you do not include this library in your application,
you should check carefully whether you need to provide some alternative
implementation for some facilities.
(For instance,
without function <CODE>_ERRORMESSAGE</CODE>,
Lua is unable to show error messages.)
<P>
<A NAME="alert"></A>
<h3> <TT>_ALERT (message)</TT></h3><A NAME="alert"></A>
Prints its only string argument to <A NAME="stderr"><TT>stderr</TT></A>.
All error messages in Lua are printed through the function stored
in the <CODE>_ALERT</CODE> global variable
(see Section&nbsp;<A HREF="#error">4.7</A>).
Therefore, a program may assign another function to this variable
to change the way such messages are shown
(for instance, for systems without <CODE>stderr</CODE>).
<P>
<h3> <TT>assert (v [, message])</TT></h3><A NAME="assert"></A>
Issues an <EM>``assertion failed!''</EM> error
when its argument <CODE>v</CODE> is <B>nil</B>.
This function is equivalent to the following Lua function:
<PRE>
       function assert (v, m)
         if not v then
           m = m or ""
           error("assertion failed!  " .. m)
         end
       end
</PRE>
<P>
<h3> <TT>call (func, arg [, mode [, errhandler]])</TT></h3><A NAME="call"></A>
<A NAME="pdf-call"></A>

Calls function <CODE>func</CODE> with
the arguments given by the table <CODE>arg</CODE>.
The call is equivalent to
<PRE>
       func(arg[1], arg[2], ..., arg[n])
</PRE>
where <CODE>n</CODE> is the result of <CODE>getn(arg)</CODE> (see Section&nbsp;<A HREF="#getn">6.1</A>).
All results from <CODE>func</CODE> are simply returned by <CODE>call</CODE>.
<P>
By default,
if an error occurs during the call to <CODE>func</CODE>,
the error is propagated.
If the string <CODE>mode</CODE> contains <CODE>"x"</CODE>,
then the call is <EM>protected</EM>.<A NAME="protected calls"></A>
In this mode, function <CODE>call</CODE> does not propagate an error,
regardless of what happens during the call.
Instead, it returns <B>nil</B> to signal the error
(besides calling the appropriated error handler).
<P>
If <CODE>errhandler</CODE> is provided,
the error function <CODE>_ERRORMESSAGE</CODE> is temporarily set to <CODE>errhandler</CODE>,
while <CODE>func</CODE> runs.
In particular, if <CODE>errhandler</CODE> is <B>nil</B>,
no error messages will be issued during the execution of the called function.
<P>
<h3> <TT>collectgarbage ([limit])</TT></h3><A NAME="collectgarbage"></A>
<P>
Sets the garbage-collection threshold for the given limit
(in Kbytes), and checks it against the byte counter.
If the new threshold is smaller than the byte counter,
then Lua immediately runs the garbage collector (see Section&nbsp;<A HREF="#GC">5.6</A>).
If <CODE>limit</CODE> is absent, it defaults to zero
(thus forcing a garbage-collection cycle).
<P>
<h3> <TT>copytagmethods (tagto, tagfrom)</TT></h3>
<A NAME="copytagmethods"></A>
Copies all tag methods from one tag to another;
returns <CODE>tagto</CODE>.
<P>
<h3> <TT>dofile (filename)</TT></h3><A NAME="dofile"></A>
Receives a file name,
opens the named file, and executes its contents as a Lua chunk,
or as pre-compiled chunks.
When called without arguments,
<CODE>dofile</CODE> executes the contents of the standard input (<CODE>stdin</CODE>).
If there is any error executing the file,
then <CODE>dofile</CODE> returns <B>nil</B>.
Otherwise, it returns the values returned by the chunk,
or a non-<B>nil</B> value if the chunk returns no values.
It issues an error when called with a non-string argument.
<P>
<h3> <TT>dostring (string [, chunkname])</TT></h3><A NAME="dostring"></A>
Executes a given string as a Lua chunk.
If there is any error executing the string,
then <CODE>dostring</CODE> returns <B>nil</B>.
Otherwise, it returns the values returned by the chunk,
or a non-<B>nil</B> value if the chunk returns no values.
The optional parameter <CODE>chunkname</CODE>
is the ``name of the chunk'',
used in error messages and debug information.
<P>
<A NAME="pdf-error"></A>
<h3> <TT>error (message)</TT></h3><A NAME="error"></A>
Calls the error handler (see Section&nbsp;<A HREF="#error">4.7</A>) and then terminates
the last protected function called
(in&nbsp;C: <CODE>lua_dofile</CODE>, <CODE>lua_dostring</CODE>,
<CODE>lua_dobuffer</CODE>, or <CODE>lua_callfunction</CODE>;
in Lua: <CODE>dofile</CODE>, <CODE>dostring</CODE>, or <CODE>call</CODE> in protected mode).
If <CODE>message</CODE> is <B>nil</B>, then the error handler is not called.
Function <CODE>error</CODE> never returns.
<P>
<h3> <TT>foreach (table, func)</TT></h3><A NAME="foreach"></A>
Executes the given <CODE>func</CODE> over all elements of <CODE>table</CODE>.
For each element, the function is called with the index and
respective value as arguments.
If the function returns any non-<B>nil</B> value,
then the loop is broken, and this value is returned
as the final value of <CODE>foreach</CODE>.
This function could be defined in Lua:
<PRE>
       function foreach (t, f)
         for i, v in t do
           local res = f(i, v)
           if res then return res end
         end
       end
</PRE>
<P>
The behavior of <CODE>foreach</CODE> is <EM>undefined</EM> if you change
the table <CODE>t</CODE> during the traversal.
<P>
<P>
<h3> <TT>foreachi (table, func)</TT></h3><A NAME="foreachi"></A>
Executes the given <CODE>func</CODE> over the
numerical indices of <CODE>table</CODE>.
For each index, the function is called with the index and
respective value as arguments.
Indices are visited in sequential order,
from&nbsp;1 to <CODE>n</CODE>,
where <CODE>n</CODE> is the result of <CODE>getn(table)</CODE> (see Section&nbsp;<A HREF="#getn">6.1</A>).
If the function returns any non-<B>nil</B> value,
then the loop is broken, and this value is returned
as the final value of <CODE>foreachi</CODE>.
This function could be defined in Lua:
<PRE>
       function foreachi (t, f)
         for i=1,getn(t) do
           local res = f(i, t[i])
           if res then return res end
         end
       end
</PRE>
<P>
<P>
<h3> <TT>getglobal (name)</TT></h3><A NAME="getglobal"></A>
Gets the value of a global variable,
or calls a tag method for ``getglobal''.
Its full semantics is explained in Section&nbsp;<A HREF="#tag-method">4.8</A>.
The string <CODE>name</CODE> does not need to be a
syntactically valid variable name.
<P>
<A NAME="getn"></A>
<h3> <TT>getn (table)</TT></h3><A NAME="getn"></A>
Returns the ``size'' of a table, when seen as a list.
If the table has an <CODE>n</CODE> field with a numeric value,
this value is the ``size'' of the table.
Otherwise, the ``size'' is the largest numerical index with a non-nil
value in the table.
This function could be defined in Lua:
<PRE>
       function getn (t)
         if type(t.n) == "number" then return t.n end
         local max = 0
         for i, _ in t do
           if type(i) == "number" and i&gt;max then max=i end
         end
         return max
       end
</PRE>
<P>
<h3> <TT>gettagmethod (tag, event)</TT></h3>
<A NAME="gettagmethod"></A>
Returns the current tag method
for a given pair <EM>(tag, event)</EM>.
This function cannot be used to get a tag method for the ``gc'' event.
(Such tag methods can only be manipulated by C&nbsp;code.)
<P>
<h3> <TT>globals ([table])</TT></h3><A NAME="globals"></A>
Returns the current table of globals.
If the argument <CODE>table</CODE> is given,
then it also sets this table as the table of globals.
<P>
<A NAME="pdf-newtag"></A>
<h3> <TT>newtag ()</TT></h3><A NAME="newtag"></A>
Returns a new tag.
<P>
<h3> <TT>next (table, [index])</TT></h3><A NAME="next"></A>
Allows a program to traverse all fields of a table.
Its first argument is a table and its second argument
is an index in this table.
<CODE>next</CODE> returns the next index of the table and the
value associated with the index.
When called with <B>nil</B> as its second argument,
<CODE>next</CODE> returns the first index
of the table and its associated value.
When called with the last index,
or with <B>nil</B> in an empty table,
<CODE>next</CODE> returns <B>nil</B>.
If the second argument is absent, then it is interpreted as <B>nil</B>.
<P>
Lua has no declaration of fields;
semantically, there is no difference between a
field not present in a table or a field with value <B>nil</B>.
Therefore, <CODE>next</CODE> only considers fields with non-<B>nil</B> values.
The order in which the indices are enumerated is not specified,
<EM>even for numeric indices</EM>
(to traverse a table in numeric order,
use a numerical <B>for</B> or the function <CODE>foreachi</CODE>).
<P>
The behavior of <CODE>next</CODE> is <EM>undefined</EM> if you change
the table during the traversal.
<P>
<h3> <TT>print (e1, e2, ...)</TT></h3><A NAME="print"></A>
Receives any number of arguments,
and prints their values using the strings returned by <CODE>tostring</CODE>.
This function is not intended for formatted output,
but only as a quick way to show a value,
for instance for debugging.
See Section&nbsp;<A HREF="#libio">6.4</A> for functions for formatted output.
<P>
<h3> <TT>rawget (table, index)</TT></h3><A NAME="rawget"></A>
Gets the real value of <CODE>table[index]</CODE>,
without invoking any tag method.
<CODE>table</CODE> must be a table,
and <CODE>index</CODE> is any value different from <B>nil</B>.
<P>
<h3> <TT>rawset (table, index, value)</TT></h3><A NAME="rawset"></A>
Sets the real value of <CODE>table[index]</CODE> to <CODE>value</CODE>,
without invoking any tag method.
<CODE>table</CODE> must be a table,
<CODE>index</CODE> is any value different from <B>nil</B>,
and <CODE>value</CODE> is any Lua value.
<P>
<h3> <TT>setglobal (name, value)</TT></h3><A NAME="setglobal"></A>
Sets the named global variable to the given value,
or calls a tag method for ``setglobal''.
Its full semantics is explained in Section&nbsp;<A HREF="#tag-method">4.8</A>.
The string <CODE>name</CODE> does not need to be a
syntactically valid variable name.
<P>
<h3> <TT>settag (t, tag)</TT></h3><A NAME="settag"></A>
Sets the tag of a given table (see Section&nbsp;<A HREF="#TypesSec">3</A>).
<CODE>tag</CODE> must be a value created with <CODE>newtag</CODE>
(see Section&nbsp;<A HREF="#pdf-newtag">6.1</A>).
<CODE>settag</CODE> returns the value of its first argument (the table).
For the safety of host programs,
it is impossible to change the tag of a userdata from Lua.
<P>
<h3> <TT>settagmethod (tag, event, newmethod)</TT></h3>
<A NAME="settagmethod"></A>
Sets a new tag method to the given pair <EM>(tag, event)</EM> and
returns the old method.
If <CODE>newmethod</CODE> is <B>nil</B>,
then <CODE>settagmethod</CODE> restores the default behavior for the given event.
This function cannot be used to set a tag method for the ``gc'' event.
(Such tag methods can only be manipulated by C&nbsp;code.)
<P>
<h3> <TT>sort (table [, comp])</TT></h3><A NAME="sort"></A>
Sorts table elements in a given order, <EM>in-place</EM>,
from <CODE>table[1]</CODE> to <CODE>table[n]</CODE>,
where <CODE>n</CODE> is the result of <CODE>getn(table)</CODE> (see Section&nbsp;<A HREF="#getn">6.1</A>).
If <CODE>comp</CODE> is given,
then it must be a function that receives two table elements,
and returns true (that is, a value different from <B>nil</B>)
when the first is less than the second
(so that <CODE>not comp(a[i+1], a[i])</CODE> will be true after the sort).
If <CODE>comp</CODE> is not given,
then the standard Lua operator <CODE>&lt;</CODE> is used instead.
<P>
The sort algorithm is <EM>not</EM> stable
(that is, elements considered equal by the given order
may have their relative positions changed by the sort).
<P>
<A NAME="pdf-tag"></A>
<h3> <TT>tag (v)</TT></h3><A NAME="tag"></A>
Allows Lua programs to test the tag of a value (see Section&nbsp;<A HREF="#TypesSec">3</A>).
It receives one argument, and returns its tag (a number).
<P>
<h3> <TT>tonumber (e [, base])</TT></h3><A NAME="tonumber"></A>
Tries to convert its argument to a number.
If the argument is already a number or a string convertible
to a number, then <CODE>tonumber</CODE> returns that number;
otherwise, it returns <B>nil</B>.
<P>
An optional argument specifies the base to interpret the numeral.
The base may be any integer between 2 and 36, inclusive.
In bases above&nbsp;10, the letter `A' (either upper or lower case)
represents&nbsp;10, `B' represents&nbsp;11, and so forth, with `Z' representing 35.
In base 10 (the default), the number may have a decimal part,
as well as an optional exponent part (see Section&nbsp;<A HREF="#coercion">4.2</A>).
In other bases, only unsigned integers are accepted.
<P>
<h3> <TT>tostring (e)</TT></h3><A NAME="tostring"></A>
Receives an argument of any type and
converts it to a string in a reasonable format.
For complete control of how numbers are converted,
use function <CODE>format</CODE>.
<P>
<P>
<P>
<h3> <TT>tinsert (table [, pos] , value)</TT></h3><A NAME="tinsert"></A>
<P>
Inserts element <CODE>value</CODE> at table position <CODE>pos</CODE>,
shifting other elements to open space, if necessary.
The default value for <CODE>pos</CODE> is <CODE>n+1</CODE>,
where <CODE>n</CODE> is the result of <CODE>getn(table)</CODE> (see Section&nbsp;<A HREF="#getn">6.1</A>),
so that a call <CODE>tinsert(t,x)</CODE> inserts <CODE>x</CODE> at the end
of table <CODE>t</CODE>.
This function also sets or increments the field <CODE>n</CODE> of the table
to <CODE>n+1</CODE>.
This function is equivalent to the following Lua function,
except that the table accesses are all <EM>raw</EM>
(that is, without tag methods):
<PRE>
       function tinsert (t, ...)
         local pos, value
         local n = getn(t)
         if arg.n == 1 then
           pos, value = n+1, arg[1]
         else
           pos, value = arg[1], arg[2]
         end
         t.n = n+1;
         for i=n,pos,-1 do
           t[i+1] = t[i]
         end
         t[pos] = value
       end
</PRE>
<P>
<h3> <TT>tremove (table [, pos])</TT></h3><A NAME="tremove"></A>
<P>
Removes from <CODE>table</CODE> the element at position <CODE>pos</CODE>,
shifting other elements to close the space, if necessary.
Returns the value of the removed element.
The default value for <CODE>pos</CODE> is <CODE>n</CODE>,
where <CODE>n</CODE> is the result of <CODE>getn(table)</CODE> (see Section&nbsp;<A HREF="#getn">6.1</A>),
so that a call <CODE>tremove(t)</CODE> removes the last element
of table <CODE>t</CODE>.
This function also sets or decrements the field <CODE>n</CODE> of the table
to <CODE>n-1</CODE>.
<P>
This function is equivalent to the following Lua function,
except that the table accesses are all <EM>raw</EM>
(that is, without tag methods):
<PRE>
       function tremove (t, pos)
         local n = getn(t)
         if n&lt;=0 then return end
         pos = pos or n
         local value = t[pos]
         for i=pos,n-1 do
           t[i] = t[i+1]
         end
         t[n] = nil
         t.n = n-1
         return value
       end
</PRE>
<P>
<A NAME="pdf-type"></A>
<h3> <TT>type (v)</TT></h3><A NAME="type"></A>
Allows Lua programs to test the type of a value.
It receives one argument, and returns its type, coded as a string.
The possible results of this function are
<CODE>"nil"</CODE> (a string, not the value <B>nil</B>),
<CODE>"number"</CODE>,
<CODE>"string"</CODE>,
<CODE>"table"</CODE>,
<CODE>"function"</CODE>,
and <CODE>"userdata"</CODE>.
<P>
<P>
<A NAME="6.2"></A>
<H2>6.2 - String Manipulation</H2>
This library provides generic functions for string manipulation,
such as finding and extracting substrings and pattern matching.
When indexing a string in Lua, the first character is at position&nbsp;1
(not at&nbsp;0, as in C).
Also,
indices are allowed to be negative and are intepreted as indexing backwards,
from the end of the string. Thus, the last character is at position <I>-1</I>,
and so on.
<P>
<h3> <TT>strbyte (s [, i])</TT></h3><A NAME="strbyte"></A>
Returns the internal numerical code of the <EM>i</EM>-th character of <CODE>s</CODE>.
If <CODE>i</CODE> is absent, then it is assumed to be&nbsp;1.
<CODE>i</CODE> may be negative.
<P>
Numerical codes are not necessarily portable across platforms.
<P>
<h3> <TT>strchar (i1, i2, ...)</TT></h3><A NAME="strchar"></A>
Receives 0 or more integers.
Returns a string with length equal to the number of arguments,
wherein each character has the internal numerical code equal
to its correspondent argument.
<P>
Numerical codes are not necessarily portable across platforms.
<P>
<h3> <TT>strfind (s, pattern [, init [, plain]])</TT></h3>
<A NAME="strfind"></A>
Looks for the first <EM>match</EM> of
<CODE>pattern</CODE> in <CODE>s</CODE>.
If it finds one, then <CODE>strfind</CODE> returns the indices of <CODE>s</CODE>
where this occurrence starts and ends;
otherwise, it returns <B>nil</B>.
If the pattern specifies captures (see <CODE>gsub</CODE> below),
the captured strings are returned as extra results.
A third, optional numerical argument <CODE>init</CODE> specifies
where to start the search;
its default value is&nbsp;1, and may be negative.
A value of&nbsp;1 as a fourth, optional argument <CODE>plain</CODE>
turns off the pattern matching facilities,
so the function does a plain ``find substring'' operation,
with no characters in <CODE>pattern</CODE> being considered ``magic''.
Note that if <CODE>plain</CODE> is given, then <CODE>init</CODE> must be given too.
<P>
<h3> <TT>strlen (s)</TT></h3><A NAME="strlen"></A>
Receives a string and returns its length.
The empty string <CODE>""</CODE> has length 0.
Embedded zeros are counted,
and so <CODE>"a\000b\000c"</CODE> has length 5.
<P>
<h3> <TT>strlower (s)</TT></h3><A NAME="strlower"></A>
Receives a string and returns a copy of that string with all
upper case letters changed to lower case.
All other characters are left unchanged.
The definition of what is an upper-case
letter depends on the current locale.
<P>
<h3> <TT>strrep (s, n)</TT></h3><A NAME="strrep"></A>
Returns a string that is the concatenation of <CODE>n</CODE> copies of
the string <CODE>s</CODE>.
<P>
<h3> <TT>strsub (s, i [, j])</TT></h3><A NAME="strsub"></A>
Returns another string, which is a substring of <CODE>s</CODE>,
starting at <CODE>i</CODE>  and running until <CODE>j</CODE>;
<CODE>i</CODE> and <CODE>j</CODE> may be negative,
If <CODE>j</CODE> is absent, then it is assumed to be equal to <I>-1</I>
(which is the same as the string length).
In particular,
the call <CODE>strsub(s,1,j)</CODE> returns a prefix of <CODE>s</CODE>
with length <CODE>j</CODE>,
and the call <CODE>strsub(s, -i)</CODE> returns a suffix of <CODE>s</CODE>
with length <CODE>i</CODE>.
<P>
<h3> <TT>strupper (s)</TT></h3><A NAME="strupper"></A>
Receives a string and returns a copy of that string with all
lower case letters changed to upper case.
All other characters are left unchanged.
The definition of what is a lower case
letter depends on the current locale.
<P>
<h3> <TT>format (formatstring, e1, e2, ...)</TT></h3><A NAME="format"></A>
<A NAME="format"></A>

Returns a formatted version of its variable number of arguments
following the description given in its first argument (which must be a string).
The format string follows the same rules as the <CODE>printf</CODE> family of
standard C&nbsp;functions.
The only differences are that the options/modifiers
<CODE>*</CODE>, <CODE>l</CODE>, <CODE>L</CODE>, <CODE>n</CODE>, <CODE>p</CODE>,
and <CODE>h</CODE> are not supported,
and there is an extra option, <CODE>q</CODE>.
The <CODE>q</CODE> option formats a string in a form suitable to be safely read
back by the Lua interpreter:
The string is written between double quotes,
and all double quotes, returns, and backslashes in the string
are correctly escaped when written.
For instance, the call
<PRE>
       format('%q', 'a string with "quotes" and \n new line')
</PRE>
will produce the string:
<PRE>
"a string with \"quotes\" and \
 new line"
</PRE>
<P>
Conversions can be applied to the <EM>n</EM>-th argument in the argument list,
rather than the next unused argument.
In this case, the conversion character <CODE>%</CODE> is replaced
by the sequence <CODE>%d$</CODE>, where <CODE>d</CODE> is a
decimal digit in the range [1,9],
giving the position of the argument in the argument list.
For instance, the call <CODE>format("%2$d -&gt; %1$03d", 1, 34)</CODE> will
result in <CODE>"34 -&gt; 001"</CODE>.
The same argument can be used in more than one conversion.
<P>
The options <CODE>c</CODE>, <CODE>d</CODE>, <CODE>E</CODE>, <CODE>e</CODE>, <CODE>f</CODE>,
<CODE>g</CODE>, <CODE>G</CODE>, <CODE>i</CODE>, <CODE>o</CODE>, <CODE>u</CODE>, <CODE>X</CODE>, and <CODE>x</CODE> all
expect a number as argument,
whereas <CODE>q</CODE> and <CODE>s</CODE> expect a string.
The <CODE>*</CODE> modifier can be simulated by building
the appropriate format string.
For example, <CODE>"%*g"</CODE> can be simulated with
<CODE>"%"..width.."g"</CODE>.
<P>
Neither the format string nor the string values to be formatted with
<CODE>%s</CODE> can contain embedded zeros.
<CODE>%q</CODE> handles string values with embedded zeros.
<P>
<h3> <TT>gsub (s, pat, repl [, n])</TT></h3>
<A NAME="gsub"></A>
Returns a copy of <CODE>s</CODE>
in which all occurrences of the pattern <CODE>pat</CODE> have been
replaced by a replacement string specified by <CODE>repl</CODE>.
<CODE>gsub</CODE> also returns, as a second value,
the total number of substitutions made.
<P>
If <CODE>repl</CODE> is a string, then its value is used for replacement.
Any sequence in <CODE>repl</CODE> of the form <CODE>%n</CODE>
with <CODE>n</CODE> between 1 and 9
stands for the value of the <EM>n</EM>-th captured substring.
<P>
If <CODE>repl</CODE> is a function, then this function is called every time a
match occurs, with all captured substrings passed as arguments,
in order (see below).
If the value returned by this function is a string,
then it is used as the replacement string;
otherwise, the replacement string is the empty string.
<P>
The last, optional parameter <CODE>n</CODE> limits
the maximum number of substitutions to occur.
For instance, when <CODE>n</CODE> is 1 only the first occurrence of
<CODE>pat</CODE> is replaced.
<P>
Here are some examples:
<PRE>
   x = gsub("hello world", "(%w+)", "%1 %1")
   --&gt; x="hello hello world world"
<P>
   x = gsub("hello world", "(%w+)", "%1 %1", 1)
   --&gt; x="hello hello world"
<P>
   x = gsub("hello world from Lua", "(%w+)%s*(%w+)", "%2 %1")
   --&gt; x="world hello Lua from"
<P>
   x = gsub("home = $HOME, user = $USER", "%$(%w+)", getenv)
   --&gt; x="home = /home/roberto, user = roberto"  (for instance)
<P>
   x = gsub("4+5 = $return 4+5$", "%$(.-)%$", dostring)
   --&gt; x="4+5 = 9"
<P>
   local t = {name="lua", version="4.0"}
   x = gsub("$name - $version", "%$(%w+)", function (v) return %t[v] end)
   --&gt; x="lua - 4.0"
<P>
   t = {n=0}
   gsub("first second word", "(%w+)", function (w) tinsert(%t, w) end)
   --&gt; t={"first", "second", "word"; n=3}
</PRE>
<P>
<P>
<A NAME="pm"></A>
<h3>Patterns</h3> 
<P>
<H4>Character Class:</H4>
a <A NAME="character class"><EM>character class</EM></A> is used to represent a set of characters.
The following combinations are allowed in describing a character class:
<DL>
<DT><B><EM>x</EM></B><DD> (where <EM>x</EM> is any magic characters
<CODE>^$()%.[]*+-?</CODE>)
- represents the character <EM>x</EM> itself.
<DT><B><TT>.</TT></B><DD> - (a dot) represents all characters.
<DT><B><TT>%a</TT></B><DD> - represents all letters.
<DT><B><TT>%c</TT></B><DD> - represents all control characters.
<DT><B><TT>%d</TT></B><DD> - represents all digits.
<DT><B><TT>%l</TT></B><DD> - represents all lower case letters.
<DT><B><TT>%p</TT></B><DD> - represents all punctuation characters.
<DT><B><TT>%s</TT></B><DD> - represents all space characters.
<DT><B><TT>%u</TT></B><DD> - represents all upper case letters.
<DT><B><TT>%w</TT></B><DD> - represents all alphanumeric characters.
<DT><B><TT>%x</TT></B><DD> - represents all hexadecimal digits.
<DT><B><TT>%z</TT></B><DD> - represents the character with representation 0.
<DT><B><TT>%<EM>x</TT></EM></B><DD> (where <EM>x</EM> is any non-alphanumeric character)  -
represents the character <EM>x</EM>.
This is the standard way to escape the magic characters.
We recommend that any punctuation character (even the non magic)
should be preceded by a <CODE>%</CODE>
when used to represent itself in a pattern.
<P>
<DT><B><TT>[char-set</TT></B>]<DD> -
represents the class which is the union of all
characters in <CODE>char-set</CODE>.
A range of characters may be specified by
separating the end characters of the range with a <CODE>-</CODE>.
All classes <CODE>%</CODE><EM>x</EM> described above may also be used as
components in a char-set.
All other characters in char-set represent themselves.
For example, <CODE>[%w_]</CODE> (or <CODE>[_%w]</CODE>)
represents all alphanumeric characters plus the underscore,
<CODE>[0-7]</CODE> represents the octal digits,
and <CODE>[0-7%l%-]</CODE> represents the octal digits plus
the lower case letters plus the <CODE>-</CODE> character.
<P>
The interaction between ranges and classes is not defined.
Therefore, patterns like <CODE>[%a-z]</CODE> or <CODE>[a-%%]</CODE>
have no meaning.
<P>
<DT><B><TT>[^char-set</TT></B>]<DD> -
represents the complement of <CODE>char-set</CODE>,
where <CODE>char-set</CODE> is interpreted as above.
</DL>
For all classes represented by single letters (<CODE>%a</CODE>, <CODE>%c</CODE>, ...),
the corresponding upper-case letter represents the complement of the class.
For instance, <CODE>%S</CODE> represents all non-space characters.
<P>
The definitions of letter, space, etc. depend on the current locale.
In particular, the class <CODE>[a-z]</CODE> may not be equivalent to <CODE>%l</CODE>.
The second form should be preferred for portability.
<P>
<H4>Pattern Item:</H4>
a <A NAME="pattern item"><EM>pattern item</EM></A> may be
<UL>
<LI>
a single character class,
which matches any single character in the class;
<LI>
a single character class followed by <CODE>*</CODE>,
which matches 0 or more repetitions of characters in the class.
These repetition items will always match the longest possible sequence;
<LI>
a single character class followed by <CODE>+</CODE>,
which matches 1 or more repetitions of characters in the class.
These repetition items will always match the longest possible sequence;
<LI>
a single character class followed by <CODE>-</CODE>,
which also matches 0 or more repetitions of characters in the class.
Unlike <CODE>*</CODE>,
these repetition items will always match the shortest possible sequence;
<LI>
a single character class followed by <CODE>?</CODE>,
which matches 0 or 1 occurrence of a character in the class;
<LI>
<TT>%<EM>n</TT></EM>, for <EM>n</EM> between 1 and 9;
such item matches a sub-string equal to the <EM>n</EM>-th captured string
(see below);
<LI>
<TT>%b<EM>xy</TT></EM>, where <EM>x</EM> and <EM>y</EM> are two distinct characters;
such item matches strings that start with&nbsp;<EM>x</EM>, end with&nbsp;<EM>y</EM>,
and where the <EM>x</EM> and <EM>y</EM> are <EM>balanced</EM>.
This means that, if one reads the string from left to right,
counting <I>+1</I> for an <EM>x</EM> and <I>-1</I> for a <EM>y</EM>,
the ending <EM>y</EM> is the first <EM>y</EM> where the count reaches 0.
For instance, the item <CODE>%b()</CODE> matches expressions with
balanced parentheses.
</UL>
<P>
<H4>Pattern:</H4>
a <A NAME="pattern"><EM>pattern</EM></A> is a sequence of pattern items.
A <CODE>^</CODE> at the beginning of a pattern anchors the match at the
beginning of the subject string.
A <CODE>$</CODE> at the end of a pattern anchors the match at the
end of the subject string.
At other positions,
<CODE>^</CODE> and <CODE>$</CODE> have no special meaning and represent themselves.
<P>
<H4>Captures:</H4>
A pattern may contain sub-patterns enclosed in parentheses,
they describe <A NAME="captures"><EM>captures</EM></A>.
When a match succeeds, the sub-strings of the subject string
that match captures are stored (<EM>captured</EM>) for future use.
Captures are numbered according to their left parentheses.
For instance, in the pattern <CODE>"(a*(.)%w(%s*))"</CODE>,
the part of the string matching <CODE>"a*(.)%w(%s*)"</CODE> is
stored as the first capture (and therefore has number&nbsp;1);
the character matching <CODE>.</CODE> is captured with number&nbsp;2,
and the part matching <CODE>%s*</CODE> has number&nbsp;3.
<P>
A pattern cannot contain embedded zeros.  Use <CODE>%z</CODE> instead.
<P>
<P>
<A NAME="mathlib"></A>
<A NAME="6.3"></A>
<H2>6.3 - Mathematical Functions</H2> 
<P>
This library is an interface to some functions of the standard C&nbsp;math library.
In addition, it registers a tag method for the binary operator <CODE>^</CODE> that
returns <I>x^y</I> when applied to numbers <CODE>x^y</CODE>.
<P>
The library provides the following functions:
<A NAME="abs"></A><A NAME="acos"></A><A NAME="asin"></A><A NAME="atan"></A>
<A NAME="atan2"></A><A NAME="ceil"></A><A NAME="cos"></A><A NAME="def"></A><A NAME="exp"></A>
<A NAME="floor"></A><A NAME="log"></A><A NAME="log10"></A><A NAME="max"></A><A NAME="min"></A>
<A NAME="mod"></A><A NAME="rad"></A><A NAME="sin"></A><A NAME="sqrt"></A><A NAME="tan"></A>
<A NAME="frexp"></A><A NAME="ldexp"></A><A NAME="random"></A><A NAME="randomseed"></A>
<PRE>
       abs  acos  asin  atan  atan2  ceil  cos  deg    exp    floor   log  log10
       max  min   mod   rad   sin    sqrt  tan  frexp  ldexp  random  randomseed
</PRE>
plus a global variable <A NAME="PI"><TT>PI</TT></A>.
Most of them
are only interfaces to the homonymous functions in the C&nbsp;library,
except that, for the trigonometric functions,
all angles are expressed in <EM>degrees</EM>, not radians.
The functions <CODE>deg</CODE> and <CODE>rad</CODE> can be used to convert
between radians and degrees.
<P>
The function <CODE>max</CODE> returns the maximum
value of its numeric arguments.
Similarly, <CODE>min</CODE> computes the minimum.
Both can be used with 1, 2, or more arguments.
<P>
The functions <CODE>random</CODE> and <CODE>randomseed</CODE> are interfaces to
the simple random generator functions <CODE>rand</CODE> and <CODE>srand</CODE>,
provided by ANSI C.
(No guarantees can be given for their statistical properties.)
The function <CODE>random</CODE>, when called without arguments,
returns a pseudo-random real number in the range <I>[0,1)</I>.
When called with a number <I>n</I>,
<CODE>random</CODE> returns a pseudo-random integer in the range <I>[1,n]</I>.
When called with two arguments, <I>l</I> and <I>u</I>,
<CODE>random</CODE> returns a pseudo-random integer in the range <I>[l,u]</I>.
<P>
<P>
<A NAME="libio"></A>
<A NAME="6.4"></A>
<H2>6.4 - I/O Facilities</H2> 
<P>
All input and output operations in Lua are done, by default,
over two <A NAME="file handles"><EM>file handles</EM></A>, one for reading and one for writing.
These handles are stored in two Lua global variables,
called <CODE>_INPUT</CODE> and <CODE>_OUTPUT</CODE>.
The global variables
<CODE>_STDIN</CODE>, <CODE>_STDOUT</CODE>, and <CODE>_STDERR</CODE>
are initialized with file descriptors for
<CODE>stdin</CODE>, <CODE>stdout</CODE>, and <CODE>stderr</CODE>.
Initially, <CODE>_INPUT=_STDIN</CODE> and <CODE>_OUTPUT=_STDOUT</CODE>.
<A NAME="_INPUT"></A><A NAME="_OUTPUT"></A>
<A NAME="_STDIN"></A><A NAME="_STDOUT"></A><A NAME="_STDERR"></A>
<P>
A file handle is a userdata containing the file stream (<CODE>FILE*</CODE>),
and with a distinctive tag created by the I/O library.
<P>
Unless otherwise stated,
all I/O functions return <B>nil</B> on failure and
some value different from <B>nil</B> on success.
<P>
<h3> <TT>openfile (filename, mode)</TT></h3><A NAME="openfile"></A>
<P>
This function opens a file,
in the mode specified in the string <CODE>mode</CODE>.
It returns a new file handle,
or, in case of errors, <B>nil</B> plus a string describing the error.
This function does not modify either <CODE>_INPUT</CODE> or <CODE>_OUTPUT</CODE>.
<P>
The <CODE>mode</CODE> string can be any of the following:
<DL>
<DT><B>``r''</B><DD> read mode;
<DT><B>``w''</B><DD> write mode;
<DT><B>``a''</B><DD> append mode;
<DT><B>``r+''</B><DD> update mode, all previous data is preserved;
<DT><B>``w+''</B><DD> update mode, all previous data is erased;
<DT><B>``a+''</B><DD> append update mode, previous data is preserved,
  writing is only allowed at the end of file.
</DL>
The <CODE>mode</CODE> string may also have a <CODE>b</CODE> at the end,
which is needed in some systems to open the file in binary mode.
This string is exactlty what is used in the standard&nbsp;C function <CODE>fopen</CODE>.
<P>
<h3> <TT>closefile (handle)</TT></h3><A NAME="closefile"></A>
<P>
This function closes the given file.
It does not modify either <CODE>_INPUT</CODE> or <CODE>_OUTPUT</CODE>.
<P>
<h3> <TT>readfrom (filename)</TT></h3><A NAME="readfrom"></A>
<P>
This function may be called in two ways.
When called with a file name, it opens the named file,
sets its handle as the value of <CODE>_INPUT</CODE>,
and returns this value.
It does not close the current input file.
When called without parameters,
it closes the <CODE>_INPUT</CODE> file,
and restores <CODE>stdin</CODE> as the value of <CODE>_INPUT</CODE>.
If this function fails, it returns <B>nil</B>,
plus a string describing the error.
<P>
If <CODE>filename</CODE> starts with a <CODE>|</CODE>,
then a <A NAME="piped input">piped input</A> is opened, via function <A NAME="popen"><TT>popen</TT></A>.
Not all systems implement pipes.
Moreover,
the number of files that can be open at the same time is
usually limited and depends on the system.
<P>
<h3> <TT>writeto (filename)</TT></h3><A NAME="writeto"></A>
<P>
This function may be called in two ways.
When called with a file name,
it opens the named file,
sets its handle as the value of <CODE>_OUTPUT</CODE>,
and returns this value.
It does not close the current output file.
Note that, if the file already exists,
then it will be <EM>completely erased</EM> with this operation.
When called without parameters,
this function closes the <CODE>_OUTPUT</CODE> file,
and restores <CODE>stdout</CODE> as the value of <CODE>_OUTPUT</CODE>.
<A NAME="closing a file"></A>
If this function fails, it returns <B>nil</B>,
plus a string describing the error.
<P>
If <CODE>filename</CODE> starts with a <CODE>|</CODE>,
then a <A NAME="piped input">piped input</A> is opened, via function <A NAME="popen"><TT>popen</TT></A>.
Not all systems implement pipes.
Moreover,
the number of files that can be open at the same time is
usually limited and depends on the system.
<P>
<h3> <TT>appendto (filename)</TT></h3><A NAME="appendto"></A>
<P>
Opens a file named <CODE>filename</CODE> and sets it as the
value of <CODE>_OUTPUT</CODE>.
Unlike the <CODE>writeto</CODE> operation,
this function does not erase any previous contents of the file;
instead, anything written to the file is appended to its end.
If this function fails, it returns <B>nil</B>,
plus a string describing the error.
<P>
<h3> <TT>remove (filename)</TT></h3><A NAME="remove"></A>
<P>
Deletes the file with the given name.
If this function fails, it returns <B>nil</B>,
plus a string describing the error.
<P>
<h3> <TT>rename (name1, name2)</TT></h3><A NAME="rename"></A>
<P>
Renames file named <CODE>name1</CODE> to <CODE>name2</CODE>.
If this function fails, it returns <B>nil</B>,
plus a string describing the error.
<P>
<h3> <TT>flush ([filehandle])</TT></h3><A NAME="flush"></A>
<P>
Saves any written data to the given file.
If <CODE>filehandle</CODE> is not specified,
then <CODE>flush</CODE> flushes all open files.
If this function fails, it returns <B>nil</B>,
plus a string describing the error.
<P>
<h3> <TT>seek (filehandle [, whence] [, offset])</TT></h3><A NAME="seek"></A>
<P>
Sets and gets the file position,
measured in bytes from the beginning of the file,
to the position given by <CODE>offset</CODE> plus a base
specified by the string <CODE>whence</CODE>, as follows:
<DL>
<DT><B>``set''</B><DD> base is position 0 (beginning of the file);
<DT><B>``cur''</B><DD> base is current position;
<DT><B>``end''</B><DD> base is end of file;
</DL>
In case of success, function <CODE>seek</CODE> returns the final file position,
measured in bytes from the beginning of the file.
If the call fails, it returns <B>nil</B>,
plus a string describing the error.
<P>
The default value for <CODE>whence</CODE> is <CODE>"cur"</CODE>,
and for <CODE>offset</CODE> is 0.
Therefore, the call <CODE>seek(file)</CODE> returns the current
file position, without changing it;
the call <CODE>seek(file, "set")</CODE> sets the position to the
beginning of the file (and returns 0);
and the call <CODE>seek(file, "end")</CODE> sets the position to the
end of the file, and returns its size.
<P>
<h3> <TT>tmpname ()</TT></h3><A NAME="tmpname"></A>
<P>
Returns a string with a file name that can safely
be used for a temporary file.
The file must be explicitly opened before its use
and removed when no longer needed.
<P>
<h3> <TT>read ([filehandle,] format1, ...)</TT></h3><A NAME="read"></A>
<P>
Reads file <CODE>_INPUT</CODE>,
or <CODE>filehandle</CODE> if this argument is given,
according to the given formats, which specify what to read.
For each format,
the function returns a string (or a number) with the characters read,
or <B>nil</B> if it cannot read data with the specified format.
When called without formats,
it uses a default format that reads the next line
(see below).
<P>
The available formats are
<DL>
<DT><B>``*n''</B><DD> reads a number;
this is the only format that returns a number instead of a string.
<DT><B>``*l''</B><DD> reads the next line
(skipping the end of line), or <B>nil</B> on end of file.
This is the default format.
<DT><B>``*a''</B><DD> reads the whole file, starting at the current position.
On end of file, it returns the empty string.
<DT><B>``*w''</B><DD> reads the next word
(maximal sequence of non--white-space characters),
skipping spaces if necessary, or <B>nil</B> on end of file.
<DT><B><EM>number</EM></B><DD> reads a string with up to that number of characters,
or <B>nil</B> on end of file.
</DL>
<P>
<h3> <TT>write ([filehandle, ] value1, ...)</TT></h3><A NAME="write"></A>
<P>
Writes the value of each of its arguments to
file <CODE>_OUTPUT</CODE>,
or to <CODE>filehandle</CODE> if this argument is given.
The arguments must be strings or numbers.
To write other values,
use <CODE>tostring</CODE> or <CODE>format</CODE> before <CODE>write</CODE>.
If this function fails, it returns <B>nil</B>,
plus a string describing the error.
<P>
<A NAME="libiosys"></A>
<A NAME="6.5"></A>
<H2>6.5 - System Facilities</H2> 
<P>
<h3> <TT>clock ()</TT></h3><A NAME="clock"></A>
<P>
Returns an approximation of the amount of CPU time
used by the program, in seconds.
<P>
<h3> <TT>date ([format])</TT></h3><A NAME="date"></A>
<P>
Returns a string containing date and time
formatted according to the given string <CODE>format</CODE>,
following the same rules of the ANSI&nbsp;C function <CODE>strftime</CODE>.
When called without arguments,
it returns a reasonable date and time representation that depends on
the host system and on the current locale.
<P>
<h3> <TT>execute (command)</TT></h3><A NAME="execute"></A>
<P>
This function is equivalent to the C&nbsp;function <CODE>system</CODE>.
It passes <CODE>command</CODE> to be executed by an operating system shell.
It returns a status code, which is system-dependent.
<P>
<h3> <TT>exit ([code])</TT></h3><A NAME="exit"></A>
<P>
Calls the C&nbsp;function <CODE>exit</CODE>,
with an optional <CODE>code</CODE>,
to terminate the program.
The default value for <CODE>code</CODE> is the success code.
<P>
<h3> <TT>getenv (varname)</TT></h3><A NAME="getenv"></A>
<P>
Returns the value of the process environment variable <CODE>varname</CODE>,
or <B>nil</B> if the variable is not defined.
<P>
<h3> <TT>setlocale (locale [, category])</TT></h3><A NAME="setlocale"></A>
<P>
This function is an interface to the ANSI&nbsp;C function <CODE>setlocale</CODE>.
<CODE>locale</CODE> is a string specifying a locale;
<CODE>category</CODE> is an optional string describing which category to change:
<CODE>"all"</CODE>, <CODE>"collate"</CODE>, <CODE>"ctype"</CODE>,
<CODE>"monetary"</CODE>, <CODE>"numeric"</CODE>, or <CODE>"time"</CODE>;
the default category is <CODE>"all"</CODE>.
The function returns the name of the new locale,
or <B>nil</B> if the request cannot be honored.
<P>
<P>
<A NAME="debugI"></A>
<!-- ====================================================================== -->
<HR>
<A NAME="7."></A>
<H1>7 - The Debug Interface</H1> 
<P>
Lua has no built-in debugging facilities.
Instead, it offers a special interface,
by means of functions and <EM>hooks</EM>,
which allows the construction of different
kinds of debuggers, profilers, and other tools
that need ``inside information'' from the interpreter.
This interface is declared in <CODE>luadebug.h</CODE>.
<P>
<A NAME="7.1"></A>
<H2>7.1 - Stack and Function Information</H2>
<P>
<A NAME="lua_getstack"></A>
The main function to get information about the interpreter stack is
<PRE>
       int lua_getstack (lua_State *L, int level, lua_Debug *ar);
</PRE>
It fills parts of a <CODE>lua_Debug</CODE> structure with
an identification of the <EM>activation record</EM>
of the function executing at a given level.
Level&nbsp;0 is the current running function,
whereas level <I>n+1</I> is the function that has called level <I>n</I>.
Usually, <CODE>lua_getstack</CODE> returns 1;
when called with a level greater than the stack depth,
it returns 0.
<P>
<A NAME="lua_Debug"></A>
The structure <CODE>lua_Debug</CODE> is used to carry different pieces of
information about an active function:
<PRE>
      typedef struct lua_Debug {
        const char *event;     /* "call", "return" */
        int currentline;       /* (l) */
        const char *name;      /* (n) */
        const char *namewhat;  /* (n) global, tag method, local, field */
        int nups;              /* (u) number of upvalues */
        int linedefined;       /* (S) */
        const char *what;      /* (S) "Lua" function, "C" function, Lua "main" */
        const char *source;    /* (S) */
        char short_src[LUA_IDSIZE]; /* (S) */
<P>
        /* private part */
        ...
      } lua_Debug;
</PRE>
<CODE>lua_getstack</CODE> fills only the private part
of this structure, for future use.
To fill in the other fields of <CODE>lua_Debug</CODE> with useful information,
call <A NAME="lua_getinfo"></A>
<PRE>
       int lua_getinfo (lua_State *L, const char *what, lua_Debug *ar);
</PRE>
This function returns 0 on error
(e.g., an invalid option in <CODE>what</CODE>).
Each character in the string <CODE>what</CODE>
selects some fields of <CODE>ar</CODE> to be filled,
as indicated by the letter in parentheses in the definition of <CODE>lua_Debug</CODE>:
`<CODE>S</CODE>' fills in the fields <CODE>source</CODE>, <CODE>linedefined</CODE>,
and <CODE>what</CODE>;
`<CODE>l</CODE>' fills in the field <CODE>currentline</CODE>, etc.
Moreover, `<CODE>f</CODE>' pushes onto the stack the function that is
running at the given level.
<P>
To get information about a function that is not active (that is,
it is not in the stack),
you push the function onto the stack,
and start the <CODE>what</CODE> string with the character <CODE>&gt;</CODE>.
For instance, to know in which line a function <CODE>f</CODE> was defined,
you can write
<PRE>
       lua_Debug ar;
       lua_getglobal(L, "f");
       lua_getinfo(L, "&gt;S", &amp;ar);
       printf("%d\n", ar.linedefined);
</PRE>
The fields of <CODE>lua_Debug</CODE> have the following meaning:
<DL>
<P>
<DT><B>source</B><DD>
If the function was defined in a string,
<CODE>source</CODE> is that string;
if the function was defined in a file,
<CODE>source</CODE> starts with a <CODE>@</CODE> followed by the file name.
<P>
<DT><B>short_src</B><DD>
A ``printable'' version of <CODE>source</CODE>, to be used in error messages.
<P>
<DT><B>linedefined</B><DD>
the line number where the definition of the function starts.
<P>
<DT><B>what</B><DD> the string <CODE>"Lua"</CODE> if this is a Lua function,
<CODE>"C"</CODE> if this is a C&nbsp;function,
or <CODE>"main"</CODE> if this is the main part of a chunk.
<P>
<DT><B>currentline</B><DD>
the current line where the given function is executing.
When no line information is available,
<CODE>currentline</CODE> is set to <I>-1</I>.
<P>
<DT><B>name</B><DD>
a reasonable name for the given function.
Because functions in Lua are first class values,
they do not have a fixed name:
Some functions may be the value of many global variables,
while others may be stored only in a table field.
The <CODE>lua_getinfo</CODE> function checks whether the given
function is a tag method or the value of a global variable.
If the given function is a tag method,
then <CODE>name</CODE> points to the event name.
If the given function is the value of a global variable,
then <CODE>name</CODE> points to the variable name.
If the given function is neither a tag method nor a global variable,
then <CODE>name</CODE> is set to <CODE>NULL</CODE>.
<P>
<DT><B>namewhat</B><DD>
Explains the previous field.
If the function is a global variable,
<CODE>namewhat</CODE> is <CODE>"global"</CODE>;
if the function is a tag method,
<CODE>namewhat</CODE> is <CODE>"tag-method"</CODE>;
otherwise <CODE>namewhat</CODE> is <CODE>""</CODE> (the empty string).
<P>
<DT><B>nups</B><DD>
Number of upvalues of a function.
<P>
</DL>
<P>
<P>
<A NAME="7.2"></A>
<H2>7.2 - Manipulating Local Variables</H2>
<P>
For the manipulation of local variables,
<CODE>luadebug.h</CODE> uses indices:
The first parameter or local variable has index&nbsp;1, and so on,
until the last active local variable.
<P>
<A NAME="lua_getlocal"></A><A NAME="lua_setlocal"></A>
The following functions allow the manipulation of the
local variables of a given activation record.
<PRE>
       const char *lua_getlocal (lua_State *L, const lua_Debug *ar, int n);
       const char *lua_setlocal (lua_State *L, const lua_Debug *ar, int n);
</PRE>
The parameter <CODE>ar</CODE> must be a valid activation record,
filled by a previous call to <CODE>lua_getstack</CODE> or
given as argument to a hook (see Section&nbsp;<A HREF="#sub-hooks">7.3</A>).
Function <CODE>lua_getlocal</CODE> gets the index of a local variable
(<CODE>n</CODE>), pushes its value onto the stack,
and returns its name.
For <CODE>lua_setlocal</CODE>,
you push the new value onto the stack,
and the function assigns that value to the variable and returns its name.
Both functions return <CODE>NULL</CODE> on failure;
that happens if the index is greater than
the number of active local variables.
<P>
As an example, the following function lists the names of all
local variables for a function at a given level of the stack:
<PRE>
       int listvars (lua_State *L, int level) {
         lua_Debug ar;
         int i = 1;
         const char *name;
         if (lua_getstack(L, level, &amp;ar) == 0)
           return 0;  /* failure: no such level in the stack */
         while ((name = lua_getlocal(L, &amp;ar, i++)) != NULL) {
           printf("%s\n", name);
           lua_pop(L, 1);  /* remove variable value */
         }
         return 1;
       }
</PRE>
<P>
<P>
<A NAME="sub-hooks"></A>
<A NAME="7.3"></A>
<H2>7.3 - Hooks</H2>
<P>
The Lua interpreter offers two hooks for debugging purposes:
a <EM>call</EM> hook and a <EM>line</EM> hook.
Both have the same type,
<A NAME="lua_Hook"></A>
<PRE>
       typedef void (*lua_Hook) (lua_State *L, lua_Debug *ar);
</PRE>
and you can set them with the following functions:
<A NAME="lua_setcallhook"></A><A NAME="lua_setlinehook"></A>
<PRE>
       lua_Hook lua_setcallhook (lua_State *L, lua_Hook func);
       lua_Hook lua_setlinehook (lua_State *L, lua_Hook func);
</PRE>
A hook is disabled when its value is <CODE>NULL</CODE>,
which is the initial value of both hooks.
The functions <CODE>lua_setcallhook</CODE> and <CODE>lua_setlinehook</CODE>
set their corresponding hooks and return their previous values.
<P>
The call hook is called whenever the
interpreter enters or leaves a function.
The <CODE>event</CODE> field of <CODE>ar</CODE> has the strings <CODE>"call"</CODE>
or <CODE>"return"</CODE>.
This <CODE>ar</CODE> can then be used in calls to <CODE>lua_getinfo</CODE>,
<CODE>lua_getlocal</CODE>, and <CODE>lua_setlocal</CODE>
to get more information about the function and to manipulate its
local variables.
<P>
The line hook is called every time the interpreter changes
the line of code it is executing.
The <CODE>event</CODE> field of <CODE>ar</CODE> has the string <CODE>"line"</CODE>,
and the <CODE>currentline</CODE> field has the line number.
Again, you can use this <CODE>ar</CODE> in other calls to the debug API.
<P>
While Lua is running a hook, it disables other calls to hooks.
Therefore, if a hook calls Lua to execute a function or a chunk,
this execution ocurrs without any calls to hooks.
<P>
<P>
<A NAME="7.4"></A>
<H2>7.4 - The Reflexive Debug Interface</H2>
<P>
The library <CODE>ldblib</CODE> provides
the functionality of the debug interface to Lua programs.
If you want to use this library,
your host application must open it,
by calling <CODE>lua_dblibopen</CODE>.
<A NAME="lua_dblibopen"></A>
<P>
You should exert great care when using this library.
The functions provided here should be used exclusively for debugging
and similar tasks (e.g., profiling).
Please resist the temptation to use them as a
usual programming tool.
They are slow and violate some (otherwise) secure aspects of the
language (e.g., privacy of local variables).
As a general rule, if your program does not need this library,
do not open it.
<P>
<P>
<h3> <TT>getinfo (function, [what])</TT></h3><A NAME="getinfo"></A>
<P>
This function returns a table with information about a function.
You can give the function directly,
or you can give a number as the value of <CODE>function</CODE>,
which means the function running at level <CODE>function</CODE> of the stack:
Level 0 is the current function (<CODE>getinfo</CODE> itself);
level 1 is the function that called <CODE>getinfo</CODE>;
and so on.
If <CODE>function</CODE> is a number larger than the number of active functions,
then <CODE>getinfo</CODE> returns <B>nil</B>.
<P>
The returned table contains all the fields returned by <CODE>lua_getinfo</CODE>,
with the string <CODE>what</CODE> describing what to get.
The default for <CODE>what</CODE> is to get all information available.
<P>
For instance, the expression <CODE>getinfo(1,"n").name</CODE> returns
the name of the current function, if a reasonable name can be found,
and <CODE>getinfo(print)</CODE> returns a table with all available information
about the <CODE>print</CODE> function.
<P>
<P>
<h3> <TT>getlocal (level, local)</TT></h3><A NAME="getlocal"></A>
<P>
This function returns the name and the value of the local variable
with index <CODE>local</CODE> of the function at level <CODE>level</CODE> of the stack.
(The first parameter or local variable has index&nbsp;1, and so on,
until the last active local variable.)
The function returns <B>nil</B> if there is no local
variable with the given index,
and raises an error when called with a <CODE>level</CODE> out of range.
(You can call <CODE>getinfo</CODE> to check whether the level is valid.)
<P>
<h3> <TT>setlocal (level, local, value)</TT></h3><A NAME="setlocal"></A>
<P>
This function assigns the value <CODE>value</CODE> to the local variable
with index <CODE>local</CODE> of the function at level <CODE>level</CODE> of the stack.
The function returns <B>nil</B> if there is no local
variable with the given index,
and raises an error when called with a <CODE>level</CODE> out of range.
<P>
<h3> <TT>setcallhook (hook)</TT></h3><A NAME="setcallhook"></A>
<P>
Sets the function <CODE>hook</CODE> as the call hook;
this hook will be called every time the interpreter starts and
exits the execution of a function.
The only argument to the call hook is the event name (<CODE>"call"</CODE> or
<CODE>"return"</CODE>).
You can call <CODE>getinfo</CODE> with level 2 to get more information about
the function being called or returning
(level&nbsp;0 is the <CODE>getinfo</CODE> function,
and level&nbsp;1 is the hook function).
When called without arguments,
this function turns off call hooks.
<CODE>setcallhook</CODE> returns the old hook.
<P>
<h3> <TT>setlinehook (hook)</TT></h3><A NAME="setlinehook"></A>
<P>
Sets the function <CODE>hook</CODE> as the line hook;
this hook will be called every time the interpreter changes
the line of code it is executing.
The only argument to the line hook is the line number the interpreter
is about to execute.
When called without arguments,
this function turns off line hooks.
<CODE>setlinehook</CODE> returns the old hook.
<P>
<P>
<A NAME="lua-sa"></A>
<!-- ====================================================================== -->
<HR>
<A NAME="8."></A>
<H1>8 - Lua Stand-alone</H1> 
<P>
Although Lua has been designed as an extension language,
to be embedded in a host C&nbsp;program,
it is frequently used as a stand-alone language.
An interpreter for Lua as a stand-alone language,
called simply <CODE>lua</CODE>,
is provided with the standard distribution.
This program can be called with any sequence of the following arguments:
<DL>
<DT><B><TT>-sNUM</TT></B><DD> sets the stack size to <TT>NUM</TT>
(if present, this must be the first option);
<DT><B><TT>-</TT> </B><DD> executes <CODE>stdin</CODE> as a file;
<DT><B><TT>-c</TT></B><DD> calls <CODE>lua_close</CODE> after running all arguments;
<DT><B><TT>-e</TT> \rm<EM>stat</EM></B><DD> executes string <CODE>stat</CODE>;
<DT><B><TT>-f filename</TT></B><DD> executes file <CODE>filename</CODE> with the
remaining arguments in table <CODE>arg</CODE>;
<DT><B><TT>-i</TT></B><DD> enters interactive mode with prompt;
<DT><B><TT>-q</TT></B><DD> enters interactive mode without prompt;
<DT><B><TT>-v</TT></B><DD> prints version information;
<DT><B><TT>var=value</TT></B><DD> sets global <CODE>var</CODE> to string <CODE>"value"</CODE>;
<DT><B><TT>filename</TT></B><DD> executes file <CODE>filename</CODE>.
</DL>
When called without arguments,
<CODE>lua</CODE> behaves as <CODE>lua -v -i</CODE> when <CODE>stdin</CODE> is a terminal,
and as <CODE>lua -</CODE> otherwise.
<P>
All arguments are handled in order, except <CODE>-c</CODE>.
For instance, an invocation like
<PRE>
       $ lua -i a=test prog.lua
</PRE>
will first interact with the user until an <CODE>EOF</CODE> in <CODE>stdin</CODE>,
then will set <CODE>a</CODE> to <CODE>"test"</CODE>,
and finally will run the file <CODE>prog.lua</CODE>.
(Here,
<CODE>$</CODE> is the shell prompt. Your prompt may be different.)
<P>
When the option <TT>-f filename</TT> is used,
all remaining arguments in the command line
are passed to the Lua program <CODE>filename</CODE> in a table called <CODE>arg</CODE>.
In this table,
the field <CODE>n</CODE> gets the index of the last argument,
and the field 0 gets <CODE>"filename"</CODE>.
For instance, in the call
<PRE>
       $ lua a.lua -f b.lua t1 t3
</PRE>
the interpreter first runs the file <TT>a.lua</TT>,
then creates a table
<PRE>
       arg = {"t1", "t3";  n = 2, [0] = "b.lua"}
</PRE>
and finally runs the file <TT>b.lua</TT>.
<A NAME="getargs"></A>
The stand-alone interpreter also provides a <CODE>getargs</CODE> function that
can be used to access <EM>all</EM> command line arguments.
For instance, if you call Lua with the line
<PRE>
       $ lua -c a b
</PRE>
then a call to <CODE>getargs</CODE> in <CODE>a</CODE> or <CODE>b</CODE> will return the table
<PRE>
       {[0] = "lua", [1] = "-c", [2] = "a", [3] = "b", n = 3}
</PRE>
<P>
In interactive mode,
a multi-line statement can be written finishing intermediate
lines with a backslash (`<CODE>\</CODE>').
If the global variable <A NAME="_PROMPT"><TT>_PROMPT</TT></A> is defined as a string,
then its value is used as the prompt.
Therefore, the prompt can be changed directly on the command line:
<PRE>
       $ lua _PROMPT='myprompt&gt; ' -i
</PRE>
or in any Lua programs by assigning to <CODE>_PROMPT</CODE>.
<P>
In Unix systems, Lua scripts can be made into executable programs
by using <CODE>chmod +x</CODE> and the&nbsp;<CODE>#!</CODE> form,
as in <CODE>#!/usr/local/bin/lua</CODE>,
or <CODE>#!/usr/local/bin/lua -f</CODE> to get other arguments.
<P>
<P>
<HR>
<A NAME="Acknowledgments"></A>
<h1>Acknowledgments</h1>
<P>
The authors would like to thank CENPES/PETROBRAS which,
jointly with TeCGraf, used early versions of
this system extensively and gave valuable comments.
The authors would also like to thank Carlos Henrique Levy,
who found the name of the game.
Lua means ``moon'' in Portuguese.
<P>
<P>
<P>
<HR>
<A NAME="Incompatibilities"></A>
<h1>Incompatibilities with Previous Versions</h1>
<P>
Lua 4.0 is a major revision of the language.
We took a great care to avoid incompatibilities with
the previous public versions of Lua,
but some differences had to be introduced.
Here is a list of all these incompatibilities.
<P>
<P>
<h2>Incompatibilities with <A NAME="version 3.2</h2>">version 3.2</h2></A>
<P>
<h3>Changes in the Language</h3>
<UL>
<P>
<LI>
All pragmas (<CODE>$debug</CODE>, <CODE>$if</CODE>, ...) have been removed.
<P>
<LI>
<B>for</B>, <B>break</B>, and <B>in</B> are now reserved words.
<P>
<LI>
Garbage-collection tag methods for tables is now obsolete.
<P>
<LI>
There is now only one tag method for order operators.
<P>
<LI>
In nested function calls like <CODE>f(g(x))</CODE>,
<EM>all</EM> return values from <CODE>g</CODE> are passed as arguments to <CODE>f</CODE>.
This only happens when <CODE>g</CODE> is the last
or the only argument to <CODE>f</CODE>.
<P>
<LI>
The pre-compiler may assume that some operators are associative,
for optimizations.
This may cause problems if these operators
have non-associative tag methods.
<P>
<LI>Old pre-compiled code is obsolete, and must be re-compiled.
<P>
</UL>
<P>
<P>
<h3>Changes in the Libraries</h3>
<UL>
<P>
<LI>
When traversing a table with <CODE>next</CODE> or <CODE>foreach</CODE>,
the table cannot be modified in any way.
<P>
<LI>
General read patterns are now obsolete.
<P>
<LI>
The functions <CODE>rawgettable</CODE> and <CODE>rawsettable</CODE>
have been renamed to <CODE>rawget</CODE> and <CODE>rawset</CODE>.
<P>
<LI>
The functions <CODE>foreachvar</CODE>, <CODE>nextvar</CODE>,
<CODE>rawsetglobal</CODE>, and <CODE>rawgetglobal</CODE> are obsolete.
You can get their functionality using table operations
over the table of globals,
which is returned by <CODE>globals</CODE>.
<P>
<LI>
<CODE>setglobal</CODE> and <CODE>sort</CODE> no longer return a value;
<CODE>type</CODE> no longer returns a second value.
<P>
<LI>
The <CODE>p</CODE> option in function <CODE>call</CODE> is now obsolete.
<P>
</UL>
<P>
<P>
<h3>Changes in the API</h3>
<UL>
<P>
<LI>
The API has been completely rewritten:
It is now fully reentrant and much clearer.
<P>
<LI>
The debug API has been completely rewritten.
<P>
</UL>
<P>
<A NAME="BNF"></A>
<A NAME="grammar"></A>
<HR>
<h1>The Complete Syntax of Lua</h1> 
<P>
<A NAME="grammar"></A>
<P>
<PRE>
<P>
       chunk ::= {stat [`<B>;</B>']}
<P>
       block ::= chunk
<P>
       stat ::=  varlist1 `<B>=</B>' explist1 <BR>	| functioncall <BR>	| <B>do</B> block <B>end</B> <BR>	| <B>while</B> exp1 <B>do</B> block <B>end</B> <BR>	| <B>repeat</B> block <B>until</B> exp1 <BR>	| <B>if</B> exp1 <B>then</B> block {<B>elseif</B> exp1 <B>then</B> block} [<B>else</B> block] <B>end</B> <BR>	| <B>return</B> [explist1] <BR>	| <B>break</B> <BR>	| <B>for</B> `<B>name</B>' `<B>=</B>' exp1 `<B>,</B>' exp1 [`<B>,</B>' exp1] <B>do</B> block <B>end</B> <BR>	| <B>for</B> `<B>name</B>' `<B>,</B>' `<B>name</B>' <B>in</B> exp1 <B>do</B> block <B>end</B> <BR>	| <B>function</B> funcname `<B>(</B>' [parlist1] `<B>)</B>' block <B>end</B> <BR>	| <B>local</B> declist [init] 
<P>
       funcname ::=  `<B>name</B>' | `<B>name</B>' `<B>.</B>' `<B>name</B>' | `<B>name</B>' `<B>:</B>' `<B>name</B>' 
<P>
       varlist1 ::= var {`<B>,</B>' var}
<P>
       var ::=  `<B>name</B>' | varorfunc `<B>[</B>' exp1 `<B>]</B>' | varorfunc `<B>.</B>' `<B>name</B>' 
<P>
       varorfunc ::= var | functioncall
<P>
       declist ::= `<B>name</B>' {`<B>,</B>' `<B>name</B>'}
<P>
       init ::= `<B>=</B>' explist1
<P>
       explist1 ::= {exp1 `<B>,</B>'} exp
<P>
       exp1 ::= exp
<P>
       exp ::=  <B>nil</B> | `<B>number</B>' | `<B>literal</B>' | var | function | upvalue <BR>	| functioncall | tableconstructor | `<B>(</B>' exp `<B>)</B>' | exp binop exp | unop exp 
<P>
<P>
       functioncall ::=  varorfunc args | varorfunc `<B>:</B>' `<B>name</B>' args 
<P>
       args ::=  `<B>(</B>' [explist1] `<B>)</B>' | tableconstructor | `<B>literal</B>' 
<P>
       function ::= <B>function</B> `<B>(</B>' [parlist1] `<B>)</B>' block <B>end</B>
<P>
       parlist1 ::=  `<B>...</B>' | `<B>name</B>' {`<B>,</B>' `<B>name</B>'} [`<B>,</B>' `<B>...</B>'] 
<P>
       upvalue ::= `<B>%</B>' `<B>name</B>'
<P>
       tableconstructor ::= `<B>{</B>' fieldlist `<B>}</B>'
       fieldlist ::=  lfieldlist | ffieldlist | lfieldlist `<B>;</B>' ffieldlist | ffieldlist `<B>;</B>' lfieldlist 
       lfieldlist ::= [lfieldlist1]
       ffieldlist ::= [ffieldlist1]
       lfieldlist1 ::= exp {`<B>,</B>' exp} [`<B>,</B>']
       ffieldlist1 ::= ffield {`<B>,</B>' ffield} [`<B>,</B>']
       ffield ::=  `<B>[</B>' exp `<B>]</B>' `<B>=</B>' exp | `<B>name</B>' `<B>=</B>' exp 
<P>
       binop ::= `<B>+</B>' | `<B>-</B>' | `<B>*</B>' | `<B>/</B>' | `<B>\^{ </B>' | `<B>..</B>' <BR>	| `<B>&lt;</B>' | `<B>&lt;=</B>' | `<B>&gt;</B>' | `<B>&gt;=</B>' | `<B>==</B>' | `<B>\&nbsp;{ </B>'=} <BR>	| <B>and</B> | <B>or</B>}
<P>
       unop ::= `<B>-</B>' | <B>not</B>
<P>
</PRE>
<P>

<HR>
<SMALL>
Last update:
Mon Nov  6 17:37:03 EDT 2000
by <A HREF="http://www.tecgraf.puc-rio.br/~lhf/">lhf</A>.
</SMALL>

</BODY>
</HTML>