summaryrefslogtreecommitdiffstats
path: root/src/scripting/lua.cpp
blob: 447b2ca1fa178669ddbc3ef7a695208c2c707376 (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
/*
 *  The Mana Server
 *  Copyright (C) 2007-2010  The Mana World Development Team
 *  Copyright (C) 2010-2013  The Mana Developers
 *
 *  This file is part of The Mana Server.
 *
 *  The Mana Server is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  any later version.
 *
 *  The Mana Server is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with The Mana Server.  If not, see <http://www.gnu.org/licenses/>.
 */


#include <cassert>

extern "C" {
#include <lualib.h>
#include <lauxlib.h>
}

#include "common/defines.h"
#include "common/resourcemanager.h"
#include "game-server/accountconnection.h"
#include "game-server/buysell.h"
#include "game-server/character.h"
#include "game-server/collisiondetection.h"
#include "game-server/effect.h"
#include "game-server/gamehandler.h"
#include "game-server/inventory.h"
#include "game-server/item.h"
#include "game-server/itemmanager.h"
#include "game-server/map.h"
#include "game-server/mapcomposite.h"
#include "game-server/mapmanager.h"
#include "game-server/monster.h"
#include "game-server/monstermanager.h"
#include "game-server/npc.h"
#include "game-server/postman.h"
#include "game-server/quest.h"
#include "game-server/state.h"
#include "game-server/statuseffect.h"
#include "game-server/statusmanager.h"
#include "game-server/triggerareacomponent.h"
#include "net/messageout.h"
#include "scripting/luautil.h"
#include "scripting/luascript.h"
#include "scripting/scriptmanager.h"
#include "utils/logger.h"
#include "utils/speedconv.h"

#include <string.h>
#include <math.h>

/*
 * This file includes all script bindings available to LUA scripts.
 * When you add or change a script binding please run the update script in the
 * docs repository!
 *
 * http://doc.manasource.org/scripting
 */

/** LUA_CATEGORY Callbacks (callbacks)
 * **Note:** You can only assign a **single** function as callback.
 * When setting a new function the old one will not be called anymore.
 * Some of this callbacks are already used for the libmana.lua. Be careful when
 * using those since they will most likely break your code in other places.
 */

/** LUA on_update_derived_attribute (callbacks)
 * on_update_derived_attribute(function ref)
 **
 * Will call the function ''ref'' when an attribute changed and other attributes
 * need recalculation. The function is expected to recalculate those then.
 *
 * **See:** [[attributes.xml]] for more info.
 *
 */
static int on_update_derived_attribute(lua_State *s)
{
    luaL_checktype(s, 1, LUA_TFUNCTION);
    BeingComponent::setUpdateDerivedAttributesCallback(getScript(s));
    return 0;
}


/** LUA on_recalculate_base_attribute (callbacks)
 * on_recalculate_base_attribute(function ref)
 **
 * Will call the function ''ref'' when an attribute base needs to be recalculated.
 * The function is expected to do this recalculation then. The engine only
 * triggers this for characters. However you can use the same function for
 * recalculating derived attributes in the
 * [[scripting#on_update_derived_attribute|on_update_derived_attribute]] callback.
 *
 * **See:** [[attributes.xml]] for more info.
 */
static int on_recalculate_base_attribute(lua_State *s)
{
    luaL_checktype(s, 1, LUA_TFUNCTION);
    BeingComponent::setRecalculateBaseAttributeCallback(getScript(s));
    return 0;
}

/** LUA on_character_death (callbacks)
 * on_character_death(function ref)
 **
 * on_character_death( function(Character*) ): void
 * Sets a listener function to the character death event.
 */
static int on_character_death(lua_State *s)
{
    luaL_checktype(s, 1, LUA_TFUNCTION);
    CharacterComponent::setDeathCallback(getScript(s));
    return 0;
}

/** LUA on_character_death_accept (callbacks)
 * on_character_death_accept(function ref)
 **
 * Will make sure that the function ''ref'' gets called with the character
 * as argument as soon a character either pressed the ok dialouge in the death
 * message or left the game while being dead.
 */
static int on_character_death_accept(lua_State *s)
{
    luaL_checktype(s, 1, LUA_TFUNCTION);
    CharacterComponent::setDeathAcceptedCallback(getScript(s));
    return 0;
}

/** LUA on_character_login (callbacks)
 * on_character_login(function ref)
 **
 * Will make sure that function ''ref'' gets called with the character
 * as argument as soon a character logged in.
 */
static int on_character_login(lua_State *s)
{
    luaL_checktype(s, 1, LUA_TFUNCTION);
    CharacterComponent::setLoginCallback(getScript(s));
    return 0;
}

/** LUA on_being_death (callbacks)
 * on_being_death(function ref)
 **
 * Will make sure that the function ''ref'' gets called with the being
 * as argument as soon a being dies.
 */
static int on_being_death(lua_State *s)
{
    luaL_checktype(s, 1, LUA_TFUNCTION);
    LuaScript::setDeathNotificationCallback(getScript(s));
    return 0;
}

/** LUA on_entity_remove (callbacks)
 * on_entity_remove(function ref)
 **
 * Will make sure that the function ''ref'' gets called with the being
 * as argument as soon a being gets removed from a map.
 */
static int on_entity_remove(lua_State *s)
{
    luaL_checktype(s, 1, LUA_TFUNCTION);
    LuaScript::setRemoveNotificationCallback(getScript(s));
    return 0;
}

/** LUA on_update (callbacks)
 * on_update(function ref)
 **
 * Will make sure that the function ''ref'' gets called every game tick.
 */
static int on_update(lua_State *s)
{
    luaL_checktype(s, 1, LUA_TFUNCTION);
    Script::setUpdateCallback(getScript(s));
    return 0;
}

/** LUA on_create_npc_delayed (callbacks)
 * on_create_npc_delayed(function ref)
 **
 * Will make sure that the function ''ref'' gets called with the
 * name, id, gender, x and y values as arguments of the npc when a npc should
 * be created at map init (Npcs defined directly in the map files use this).
 */
static int on_create_npc_delayed(lua_State *s)
{
    luaL_checktype(s, 1, LUA_TFUNCTION);
    Script::setCreateNpcDelayedCallback(getScript(s));
    return 0;
}

/** LUA on_map_initialize (callbacks)
 * on_map_initialize(function ref)
 **
 * Will make sure that the function ''ref'' gets called with the initialized
 * map as current map when the map is initialized.
 */
static int on_map_initialize(lua_State *s)
{
    luaL_checktype(s, 1, LUA_TFUNCTION);
    MapComposite::setInitializeCallback(getScript(s));
    return 0;
}

/** LUA on_craft (callbacks)
 * on_craft(function ref)
 **
 * Will make sure that the function ''ref'' gets called with the the crafting
 * character and a table with the recipes {(id, amount}) when a character
 * performs crafting.
 */
static int on_craft(lua_State *s)
{
    luaL_checktype(s, 1, LUA_TFUNCTION);
    ScriptManager::setCraftCallback(getScript(s));
    return 0;
}

/** LUA on_mapupdate (callbacks)
 * on_mapupdate(function ref)
 **
 * Will make sure that the function ''ref'' gets called with the the map id
 * as argument for each game tick and map.
 */
static int on_mapupdate(lua_State *s)
{
    luaL_checktype(s, 1, LUA_TFUNCTION);
    MapComposite::setUpdateCallback(getScript(s));
    return 0;
}


/** LUA_CATEGORY Creation and removal of stuff (creation)
 */

/** LUA npc_create (creation)
 * npc_create(string name, int spriteID, int gender, int x, int y,
 *            function talkfunct, function updatefunct)
 **
 * **Return value:** A handle to the created NPC.
 *
 * Creates a new NPC with the name ''name'' at the coordinates ''x'':''y''
 * which appears to the players with the appearence listed in their npcs.xml
 * under ''spriteID'' and the gender ''gender''. Every game tick the function
 * ''updatefunct'' is called with the handle of the NPC. When a character talks
 * to the NPC the function ''talkfunct'' is called with the NPC handle and the
 * character handle.
 *
 * For setting the gender you can use the constants defined in the
 * libmana-constants.lua:
 *
 * | 0 | GENDER_MALE         |
 * | 1 | GENDER_FEMALE       |
 * | 2 | GENDER_UNSPECIFIED  |
 */
static int npc_create(lua_State *s)
{
    const char *name = luaL_checkstring(s, 1);
    const int id = luaL_checkint(s, 2);
    const int gender = luaL_checkint(s, 3);
    const int x = luaL_checkint(s, 4);
    const int y = luaL_checkint(s, 5);

    if (!lua_isnoneornil(s, 6))
        luaL_checktype(s, 6, LUA_TFUNCTION);
    if (!lua_isnoneornil(s, 7))
        luaL_checktype(s, 7, LUA_TFUNCTION);

    MapComposite *m = checkCurrentMap(s);

    NpcComponent *npcComponent = new NpcComponent(id);

    Entity *npc = new Entity(OBJECT_NPC);
    auto *actorComponent = new ActorComponent(*npc);
    npc->addComponent(actorComponent);
    auto *beingComponent = new BeingComponent(*npc);
    npc->addComponent(beingComponent);
    npc->addComponent(npcComponent);
    // some health so it doesn't spawn dead
    beingComponent->setAttribute(*npc, ATTR_MAX_HP, 100);
    beingComponent->setAttribute(*npc, ATTR_HP, 100);
    beingComponent->setName(name);
    beingComponent->setGender(getGender(gender));

    actorComponent->setWalkMask(Map::BLOCKMASK_WALL | Map::BLOCKMASK_MONSTER |
                                Map::BLOCKMASK_CHARACTER);
    npc->setMap(m);
    actorComponent->setPosition(*npc, Point(x, y));

    if (lua_isfunction(s, 6))
    {
        lua_pushvalue(s, 6);
        npcComponent->setTalkCallback(luaL_ref(s, LUA_REGISTRYINDEX));
    }

    if (lua_isfunction(s, 7))
    {
        lua_pushvalue(s, 7);
        npcComponent->setUpdateCallback(luaL_ref(s, LUA_REGISTRYINDEX));
    }

    GameState::enqueueInsert(npc);
    push(s, npc);
    return 1;
}

/** LUA npc_enable (creation)
 * npc_disable(handle npc)
 **
 * Re-enables an NPC that got disabled before.
 */
static int npc_enable(lua_State *s)
{
    Entity *npc = checkNpc(s, 1);
    npc->getComponent<NpcComponent>()->setEnabled(true);
    GameState::enqueueInsert(npc);
    return 0;
}

/** LUA npc_disable (creation)
 * npc_disable(handle npc)
 **
 * Disable an NPC.
 */
static int npc_disable(lua_State *s)
{
    Entity *npc = checkNpc(s, 1);
    npc->getComponent<NpcComponent>()->setEnabled(false);
    GameState::remove(npc);
    return 0;
}

/** LUA monster_create (creation)
 * monster_create(int monsterID, int x, int y)
 * monster_create(string monstername, int x, int y)
 **
 * **Return value:** A handle to the created monster.
 *
 * Spawns a new monster of type ''monsterID'' or ''monstername'' on the current
 * map on the pixel coordinates ''x'':''y''.
 */
static int monster_create(lua_State *s)
{
    MonsterClass *monsterClass = checkMonsterClass(s, 1);
    const int x = luaL_checkint(s, 2);
    const int y = luaL_checkint(s, 3);
    MapComposite *m = checkCurrentMap(s);

    Entity *monster = new Entity(OBJECT_MONSTER);
    auto *actorComponent = new ActorComponent(*monster);
    monster->addComponent(actorComponent);
    monster->addComponent(new BeingComponent(*monster));
    monster->addComponent(new MonsterComponent(*monster, monsterClass));
    monster->setMap(m);
    actorComponent->setPosition(*monster, Point(x, y));
    GameState::enqueueInsert(monster);

    push(s, monster);
    return 1;
}

/** LUA entity:remove (creation)
 * entity:remove()
 **
 * Removes the entity from its current map.
 */
static int entity_remove(lua_State *s)
{
    GameState::remove(LuaEntity::check(s, 1));
    return 0;
}

/** LUA trigger_create (creation)
 * trigger_create(int x, int y, int width, int height,
 *                function trigger_function, int arg, bool once)
 **
 * Creates a new trigger area with the given ''height'' and ''width'' in pixels
 * at the map position ''x'':''y'' in pixels. When a being steps into this area
 * the function  ''trigger_function'' is called with the being handle and
 * ''arg'' as arguments. When ''once'' is false the function is called every
 * game tick the being is inside the    area. When ''once'' is true it is only
 * called again when the being leaves and reenters the area.
 */
static int trigger_create(lua_State *s)
{
    const int x = luaL_checkint(s, 1);
    const int y = luaL_checkint(s, 2);
    const int width = luaL_checkint(s, 3);
    const int height = luaL_checkint(s, 4);
    luaL_checktype(s, 5, LUA_TFUNCTION);
    const int id = luaL_checkint(s, 6);

    if (!lua_isboolean(s, 7))
    {
        luaL_error(s, "trigger_create called with incorrect parameters.");
        return 0;
    }

    Script *script = getScript(s);
    MapComposite *m = checkCurrentMap(s, script);

    const bool once = lua_toboolean(s, 7);

    Script::Ref function;
    lua_pushvalue(s, 5);
    script->assignCallback(function);
    lua_pop(s, 1);

    Entity *triggerEntity = new Entity(OBJECT_OTHER, m);

    ScriptAction *action = new ScriptAction(script, function, id);
    Rectangle r = { x, y, width, height };
    TriggerAreaComponent *area = new TriggerAreaComponent(r, action, once);

    triggerEntity->addComponent(area);

    LOG_INFO("Created script trigger at " << x << "," << y
             << " (" << width << "x" << height << ") id: " << id);

    bool ret = GameState::insertOrDelete(triggerEntity);
    lua_pushboolean(s, ret);
    return 1;
}

/** LUA effect_create (creation)
 * effect_create(int id, int x, int y)
 * effect_create(int id, being b)
 **
 * Triggers the effect ''id'' from the clients effects.xml
 * (particle and/or sound) at map location ''x'':''y'' or on being ''b''.
 * This has no effect on gameplay.
 *
 * **Warning:** Remember that clients might switch off particle effects for
 * performance reasons. Thus you should not use this for important visual
 * input.
 */
static int effect_create(lua_State *s)
{
    const int id = luaL_checkint(s, 1);

    if (lua_isuserdata(s, 2))
    {
        // being mode
        Entity *b = checkBeing(s, 2);
        Effects::show(id, b);
    }
    else
    {
        // positional mode
        int x = luaL_checkint(s, 2);
        int y = luaL_checkint(s, 3);
        MapComposite *m = checkCurrentMap(s);
        Effects::show(id, m, Point(x, y));
    }

    return 0;
}

/** LUA drop_item (creation)
 * drop_item(int x, int y, int id [, int number])
 * drop_item(int x, int y, string name[, int number])
 **
 * Creates an item stack on the floor.
 */
static int item_drop(lua_State *s)
{
    const int x = luaL_checkint(s, 1);
    const int y = luaL_checkint(s, 2);
    ItemClass *ic = checkItemClass(s, 3);
    const int number = luaL_optint(s, 4, 1);
    MapComposite *map = checkCurrentMap(s);

    Entity *item = Item::create(map, Point(x, y), ic, number);
    GameState::enqueueInsert(item);
    return 0;
}

/** LUA_CATEGORY Input and output (input)
 */

/** LUA say (input)
 * say(string message)
 **
 * **Warning:** May only be called from an NPC talk function.
 *
 * Shows an NPC dialog box on the screen of displaying the string ''message''.
 * Idles the current thread until the user click "OK".
 */
static int say(lua_State *s)
{
    const char *m = luaL_checkstring(s, 1);

    Script::Thread *thread = checkCurrentThread(s);
    Entity *npc = thread->getContext().npc;
    Entity *character = thread->getContext().character;
    if (!(npc && character))
        luaL_error(s, "not in npc conversation");

    MessageOut msg(GPMSG_NPC_MESSAGE);
    msg.writeInt16(npc->getComponent<ActorComponent>()->getPublicID());
    msg.writeString(m);
    gameHandler->sendTo(character, msg);

    thread->mState = Script::ThreadPaused;
    return lua_yield(s, 0);
}

/** LUA ask (input)
 * ask(item1, item2, ... itemN)
 **
 * **Return value:** Number of the option the player selected (starting with 1).
 *
 * **Warning:** May only be called from an NPC talk function.
 *
 * Shows an NPC dialog box on the users screen with a number of dialog options
 * to choose from. Idles the current thread until the user selects one or
 * aborts the current thread when the user clicks "cancel".
 *
 * Items are either strings or tables of strings (indices are ignored,
 * but presumed to be taken in order). So,
 * ''ask("A", {"B", "C", "D"}, "E")'' is the same as
 * ''ask("A", "B", "C", "D", "E")''.
 */
static int ask(lua_State *s)
{
    Script::Thread *thread = checkCurrentThread(s);
    Entity *npc = thread->getContext().npc;
    Entity *character = thread->getContext().character;
    if (!(npc && character))
        luaL_error(s, "not in npc conversation");

    MessageOut msg(GPMSG_NPC_CHOICE);
    msg.writeInt16(npc->getComponent<ActorComponent>()->getPublicID());
    for (int i = 1, i_end = lua_gettop(s); i <= i_end; ++i)
    {
        if (lua_isstring(s, i))
        {
            msg.writeString(lua_tostring(s, i));
        }
        else if (lua_istable(s, i))
        {
            lua_pushnil(s);
            while (lua_next(s, i) != 0)
            {
                if (lua_isstring(s, -1))
                {
                    msg.writeString(lua_tostring(s, -1));
                }
                else
                {
                    luaL_error(s, "ask called with incorrect parameters.");
                    return 0;
                }
                lua_pop(s, 1);
            }
        }
        else
        {
            luaL_error(s, "ask called with incorrect parameters.");
            return 0;
        }
    }
    gameHandler->sendTo(character, msg);

    thread->mState = Script::ThreadExpectingNumber;
    return lua_yield(s, 0);
}

/** LUA ask_number (input)
 * ask_number(min_num, max_num, [default_num])
 **
 * **Return value:** The number the player entered into the field.
 *
 * **Warning:** May only be called from an NPC talk function.
 *
 * Shows a dialog box to the user which allows him to choose a number between
 * ''min_num'' and ''max_num''. If ''default_num'' is set this number will be
 * uses as default.  Otherwise ''min_num'' will be the default.
 */
static int ask_number(lua_State *s)
{
    int min = luaL_checkint(s, 1);
    int max = luaL_checkint(s, 2);
    int defaultValue = luaL_optint(s, 3, min);

    Script::Thread *thread = checkCurrentThread(s);
    Entity *npc = thread->getContext().npc;
    Entity *character = thread->getContext().character;
    if (!(npc && character))
        luaL_error(s, "not in npc conversation");

    MessageOut msg(GPMSG_NPC_NUMBER);
    msg.writeInt16(npc->getComponent<ActorComponent>()->getPublicID());
    msg.writeInt32(min);
    msg.writeInt32(max);
    msg.writeInt32(defaultValue);
    gameHandler->sendTo(character, msg);

    thread->mState = Script::ThreadExpectingNumber;
    return lua_yield(s, 0);
}

/** LUA ask_string (input)
 * ask_string()
 **
 * **Return value:** The string the player entered.
 *
 * **Warning:** May only be called from an NPC talk function.
 *
 * Shows a dialog box to a user which allows him to enter a text.
 */
static int ask_string(lua_State *s)
{
    Script::Thread *thread = checkCurrentThread(s);
    Entity *npc = thread->getContext().npc;
    Entity *character = thread->getContext().character;
    if (!(npc && character))
        luaL_error(s, "not in npc conversation");

    MessageOut msg(GPMSG_NPC_STRING);
    msg.writeInt16(npc->getComponent<ActorComponent>()->getPublicID());
    gameHandler->sendTo(character, msg);

    thread->mState = Script::ThreadExpectingString;
    return lua_yield(s, 0);
}

/** LUA npc_post (input)
 * npc_post()
 **
 * Starts retrieving post. Better not try to use it so far.
 */
static int npc_post(lua_State *s)
{
    const Script::Context *context = getScript(s)->getContext();
    Entity *npc = context->npc;
    Entity *character = context->character;

    MessageOut msg(GPMSG_NPC_POST);
    msg.writeInt16(npc->getComponent<ActorComponent>()->getPublicID());
    gameHandler->sendTo(character, msg);

    return 0;
}

/** LUA entity:say (input)
 * entity:say(string message)
 **
 * Makes this entity (which can be a character, monster or NPC), speak the
 * string ''message'' as if it was entered by a player in the chat bar.
 */
static int entity_say(lua_State *s)
{
    Entity *actor = checkActor(s, 1);
    const char *message = luaL_checkstring(s, 2);
    GameState::sayAround(actor, message);
    return 0;
}

/** LUA entity:message (input)
 * entity:message(string message)
 **
 * Delivers the string ''message'' to this entity (which needs to be a
 * character). It will appear in the chatlog as a private message from
 * "Server".
 */
static int entity_message(lua_State *s)
{
    Entity *character = checkCharacter(s, 1);
    const char *message = luaL_checkstring(s, 2);

    GameState::sayTo(character, nullptr, message);
    return 0;
}

/** LUA announce (input)
 * announce(string message [, string sender])
 **
 * Sends a global announce with the given ''message'' and ''sender''. If no
 * ''sender'' is passed "Server" will be used as sender.
 */
static int announce(lua_State *s)
{
    const char *message = luaL_checkstring(s, 1);
    const char *sender = luaL_optstring(s, 2, "Server");

    MessageOut msg(GAMSG_ANNOUNCE);
    msg.writeString(message);
    msg.writeInt16(0); // Announce from server so id = 0
    msg.writeString(sender);
    accountHandler->send(msg);
    return 0;
}


/** LUA_CATEGORY Inventory interaction (inventory)
 */

/** LUA trade (inventory)
 * trade(bool mode,
 *       { int item1id, int item1amount, int item1cost }, ...,
 *       { int itemNid, int itemNamount, int itemNcost })
 * trade(bool mode,
 *       { string item1name, int item1amount, int item1cost }, ...,
 *       { string itemNname, int itemNamount, int itemNcost })
 **
 * FIXME: Move into a seperate file
 * Opens a trade window from an NPC conversation. ''mode''
 * is true for selling and false for buying. You have to set each items the NPC
 * is buying/selling,    the cost and the maximum amount in {}.
 *
 * **Note:** If the fourth parameters (table type) is omitted or invalid, and
 * the mode set to sell (true),
 * the whole player inventory is then sellable.
 *
 * **N.B.:** Be sure to put a ''value'' (item cost) parameter in your items.xml
 * to permit the player to sell it when using this option.
 *
 * **Return values:**
 *   * **0** when a trade has been started
 *   * **1** when there is no buy/sellable items
 *   * **2** in case of errors.
 *
 * **Examples:**
 * <code lua trade.lua>
 *     -- "A buy sample."
 *     local buycase = trade(false, {
 *         {"Sword", 10, 20},
 *         {"Bow", 10, 30},
 *         {"Dagger", 10, 50}
 *     })
 *     if buycase == 0 then
 *       say("What do you want to buy?")
 *     elseif buycase == 1 then
 *       say("I've got no items to sell.")
 *     else
 *       say("Hmm, something went wrong... Ask a scripter to
 *       fix the buying mode!")
 *     end
 *
 * -- ...
 *
 *    -- "Example: Let the player sell only pre-determined items."
 *    local sellcase = trade(true, {
 *                      {"Sword", 10, 20},
 *                      {"Bow", 10, 30},
 *                      {"Dagger", 10, 200},
 *                      {"Knife", 10, 300},
 *                      {"Arrow", 10, 500},
 *                      {"Cactus Drink", 10, 25}
 *     })
 *     if sellcase == 0 then
 *       say("Here we go:")
 *     elseif sellcase == 1 then
 *       say("I'm not interested by your items.")
 *     else
 *       say("Hmm, something went wrong...")
 *       say("Ask a scripter to fix me!")
 *     end
 *
 * -- ...
 *
 *     -- "Example: Let the player sell every item with a 'value' parameter in
 *     the server's items.xml file
 *     local sellcase = trade(true)
 *     if sellcase == 0 then
 *       say("Ok, what do you want to sell:")
 *     elseif sellcase == 1 then
 *       say("I'm not interested by any of your items.")
 *     else
 *       say("Hmm, something went wrong...")
 *       say("Ask a scripter to fix me!")
 *     end
 * </code>
 */
static int trade(lua_State *s)
{
    const Script::Context *context = getScript(s)->getContext();
    Entity *npc = context->npc;
    Entity *character = context->character;

    luaL_argcheck(s, lua_isboolean(s, 1), 1, "boolean expected");
    bool sellMode = lua_toboolean(s, 1);

    BuySell *t = new BuySell(character, sellMode);
    if (!lua_istable(s, 2))
    {
        if (sellMode)
        {
            // Can sell everything
            if (!t->registerPlayerItems())
            {
                // No items to sell in player inventory
                t->cancel();
                lua_pushinteger(s, 1);
                return 1;
            }

            if (t->start(npc))
            {
                lua_pushinteger(s, 0);
                return 1;
            }
            else
            {
                lua_pushinteger(s, 1);
                return 1;
            }
        }
        else
        {
            raiseWarning(s, "trade[Buy] called with invalid "
                         "or empty items table parameter.");
            t->cancel();
            lua_pushinteger(s, 2);
            return 1;
        }
    }

    int nbItems = 0;

    lua_pushnil(s);
    while (lua_next(s, 2))
    {
        if (!lua_istable(s, -1))
        {
            raiseWarning(s, "trade called with invalid "
                         "or empty items table parameter.");
            t->cancel();
            lua_pushinteger(s, 2);
            return 1;
        }

        int v[3];
        for (int i = 0; i < 3; ++i)
        {
            lua_rawgeti(s, -1, i + 1);
            if (i == 0) // item id or name
            {
                ItemClass *it = getItemClass(s, -1);

                if (!it)
                {
                    raiseWarning(s, "trade called with incorrect "
                                 "item id or name.");
                    t->cancel();
                    lua_pushinteger(s, 2);
                    return 1;
                }
                v[0] = it->getDatabaseID();
            }
            else if (!lua_isnumber(s, -1))
            {
                raiseWarning(s, "trade called with incorrect parameters "
                             "in item table.");
                t->cancel();
                lua_pushinteger(s, 2);
                return 1;
            }
            else
            {
                v[i] = lua_tointeger(s, -1);
            }
            lua_pop(s, 1);
        }
        if (t->registerItem(v[0], v[1], v[2]))
            nbItems++;
        lua_pop(s, 1);
    }

    if (nbItems == 0)
    {
        t->cancel();
        lua_pushinteger(s, 1);
        return 1;
    }
    if (t->start(npc))
    {
        lua_pushinteger(s, 0);
        return 1;
    }
    else
    {
        lua_pushinteger(s, 1);
        return 1;
    }
}

/** LUA entity:inv_count (inventory)
 * entity:inv_count(bool inInventory, bool inEquipment,
 *                  int id1, ..., int idN)
 * entity:inv_count(bool inInventory, bool inEquipment,
 *                  string name1, ..., string nameN)
 **
 * Valid only for character entities.
 *
 * The boolean values ''inInventory'' and ''inEquipment'' make possible to
 * select whether equipped or carried items must be counted.
 *
 * **Return values:** A number of integers with the amount of items ''id'' or
 * ''name'' carried or equipped by the character.
 */
static int entity_inv_count(lua_State *s)
{
    Entity *q = checkCharacter(s, 1);
    if (!lua_isboolean(s, 2) || !lua_isboolean(s, 3))
    {
        luaL_error(s, "inv_count called with incorrect parameters.");
        return 0;
    }

    bool inInventory = lua_toboolean(s, 2);
    bool inEquipment = lua_toboolean(s, 3);

    int nb_items = lua_gettop(s) - 3;
    Inventory inv(q);

    int nb = 0;
    for (int i = 4; i < nb_items + 4; ++i)
    {
        ItemClass *it = checkItemClass(s, i);
        nb = inv.count(it->getDatabaseID(), inInventory, inEquipment);
        lua_pushinteger(s, nb);
    }
    return nb_items;
}

/** LUA entity:inv_change (inventory)
 * entity:inv_change(int id1, int number1, ..., int idN, numberN)
 * entity:inv_change(string name1, int number1, ..., string nameN, numberN)
 **
 * Valid only for character entities.
 *
 * Changes the number of items with the item ID ''id'' or ''name'' owned by
 * this character by ''number''. You can change any number of items with this
 * function by passing multiple ''id'' or ''name'' and ''number'' pairs.
 * A failure can be caused by trying to take items the character doesn't possess.
 *
 * **Return value:** Boolean true on success, boolean false on failure.
 *
 * **Warning:** When one of the operations fails the following operations are
 * ignored but these before are executed. For that reason you should always
 * check if the character possesses items you are taking away using
 * entity:inv_count.
 */
static int entity_inv_change(lua_State *s)
{
    Entity *q = checkCharacter(s, 1);
    int nb_items = (lua_gettop(s) - 1) / 2;
    Inventory inv(q);
    for (int i = 0; i < nb_items; ++i)
    {
        if (!lua_isnumber(s, i * 2 + 3))
        {
            luaL_error(s, "inv_change called with "
                       "incorrect parameters.");
            return 0;
        }

        int nb = lua_tointeger(s, i * 2 + 3);
        ItemClass *ic = checkItemClass(s, i * 2 + 2);
        int id = ic->getDatabaseID();
        if (nb < 0)
        {
            // Removing too much item is a success as for the scripter's
            // point of view. We log it anyway.
            nb = inv.remove(id, -nb);
            if (nb)
            {
                LOG_WARN("inv_change removed more items than owned: "
                     << "character: "
                     << q->getComponent<BeingComponent>()->getName()
                     << " item id: " << id);
            }
        }
        else
        {
            nb = inv.insert(id, nb);
            if (nb)
            {
                const Point &position =
                        q->getComponent<ActorComponent>()->getPosition();
                Entity *item = Item::create(q->getMap(), position, ic, nb);
                GameState::enqueueInsert(item);
            }
        }
    }
    lua_pushboolean(s, 1);
    return 1;
}

/** LUA entity:inventory (inventory)
 * entity:inventory(): table[]{slot, item id, name, amount}
 **
 * Valid only for character entities.
 *
 * Used to get a full view of a character's inventory.
 * This is not the preferred way to know whether an item is in the character's
 * inventory:
 * Use entity:inv_count for simple cases.
 *
 * **Return value:** A table containing all the info about the character's
 * inventory. Empty slots are not listed.
 *
 * **Example of use:**
 * <code lua>
 * local inventory_table = ch:inventory()
 * for i = 1, #inventory_table do
 *     item_message = item_message.."\n"..inventory_table[i].slot..", "
 *         ..inventory_table[i].id..", "..inventory_table[i].name..", "
 *         ..inventory_table[i].amount
 * end
 * </code>
 */
static int entity_get_inventory(lua_State *s)
{
    Entity *q = checkCharacter(s, 1);

    // Create a lua table with the inventory ids.
    const InventoryData invData = q->getComponent<CharacterComponent>()
            ->getPossessions().getInventory();

    lua_newtable(s);
    int firstTableStackPosition = lua_gettop(s);
    int tableIndex = 1;

    for (InventoryData::const_iterator it = invData.begin(),
        it_end = invData.end(); it != it_end; ++it)
    {
        if (!it->second.itemId || !it->second.amount)
            continue;

        // Create the sub-table (value of the main one)
        lua_createtable(s, 0, 4);
        int subTableStackPosition = lua_gettop(s);
        // Stores the item info in it.
        lua_pushliteral(s, "slot");
        lua_pushinteger(s, it->first); // The slot id
        lua_settable(s, subTableStackPosition);

        lua_pushliteral(s, "id");
        lua_pushinteger(s, it->second.itemId);
        lua_settable(s, subTableStackPosition);

        lua_pushliteral(s, "name");
        push(s, itemManager->getItem(it->second.itemId)->getName());
        lua_settable(s, subTableStackPosition);

        lua_pushliteral(s, "amount");
        lua_pushinteger(s, it->second.amount);
        lua_settable(s, subTableStackPosition);

        // Add the sub-table as value of the main one.
        lua_rawseti(s, firstTableStackPosition, tableIndex);
        ++tableIndex;
    }

    return 1;
}

/** LUA entity:equipment (inventory)
 * entity:equipment(): table[](slot, item id, name)}
 **
 * Valid only for character entities.
 *
 * Used to get a full view of a character's equipment.
 * This is not the preferred way to know whether an item is equipped:
 * Use entity:inv_count for simple cases.
 *
 * **Return value:** A table containing all the info about the character's
 * equipment. Empty slots are not listed.
 *
 * **Example of use:**
 * <code lua>
 * local equipment_table = ch:equipment()
 * for i = 1, #equipment_table do
 *     item_message = item_message.."\n"..equipment_table[i].slot..", "
 *         ..equipment_table[i].id..", "..equipment_table[i].name
 * end
 * </code>
 */
static int entity_get_equipment(lua_State *s)
{
    Entity *q = checkCharacter(s, 1);

    // Create a lua table with the inventory ids.
    const EquipData equipData = q->getComponent<CharacterComponent>()
            ->getPossessions().getEquipment();

    lua_newtable(s);
    int firstTableStackPosition = lua_gettop(s);
    int tableIndex = 1;

    std::set<unsigned> itemInstances;

    for (EquipData::const_iterator it = equipData.begin(),
        it_end = equipData.end(); it != it_end; ++it)
    {
        if (!it->second.itemId || !it->second.itemInstance)
            continue;

        // Only count multi-slot items once.
        if (!itemInstances.insert(it->second.itemInstance).second)
            continue;

        // Create the sub-table (value of the main one)
        lua_createtable(s, 0, 3);
        int subTableStackPosition = lua_gettop(s);
        // Stores the item info in it.
        lua_pushliteral(s, "slot");
        lua_pushinteger(s, it->first); // The slot id
        lua_settable(s, subTableStackPosition);

        lua_pushliteral(s, "id");
        lua_pushinteger(s, it->second.itemId);
        lua_settable(s, subTableStackPosition);

        lua_pushliteral(s, "name");
        push(s, itemManager->getItem(it->second.itemId)->getName());
        lua_settable(s, subTableStackPosition);

        // Add the sub-table as value of the main one.
        lua_rawseti(s, firstTableStackPosition, tableIndex);
        ++tableIndex;
    }

    return 1;
}

/** LUA entity:equip_slot (inventory)
 * entity:equip_slot(int slot)
 **
 * Valid only for character entities.
 *
 * Makes the character equip the item in the given inventory slot.
 */
static int entity_equip_slot(lua_State *s)
{
    Entity *ch = checkCharacter(s, 1);
    int inventorySlot = luaL_checkint(s, 2);

    Inventory inv(ch);
    lua_pushboolean(s, inv.equip(inventorySlot));
    return 1;
}

/** LUA entity:equip_item (inventory)
 * entity:equip_item(int item_id)
 * entity:equip_item(string item_name)
 **
 * Valid only for character entities.
 *
 * Makes the character equip the item id when it exists in the player's
 * inventory.
 *
 * **Return value:** true if equipping suceeded. false otherwise.
 */
static int entity_equip_item(lua_State *s)
{
    Entity *ch = checkCharacter(s, 1);
    ItemClass *it = checkItemClass(s, 2);

    Inventory inv(ch);

    int inventorySlot = inv.getFirstSlot(it->getDatabaseID());
    bool success = false;

    if (inventorySlot > -1)
        success = inv.equip(inventorySlot);

    lua_pushboolean(s, success);
    return 1;
}

/** LUA entity:unequip_slot (inventory)
 * entity:unequip_slot(int slot)
 **
 * Valid only for character entities.
 *
 * Makes the character unequip the item in the given equipment slot.
 *
 * **Return value:** true upon success. false otherwise.
 */
static int entity_unequip_slot(lua_State *s)
{
    Entity *ch = checkCharacter(s, 1);
    int equipmentSlot = luaL_checkint(s, 2);

    Inventory inv(ch);

    lua_pushboolean(s, inv.unequip(inv.getSlotItemInstance(equipmentSlot)));
    return 1;
}

/** LUA entity:unequip_item (inventory)
 * entity:unequip_item(int item_id)
 * entity:unequip_item(string item_name)
 **
 * Valid only for character entities.
 *
 * Makes the character unequip the item(s) corresponding to the id when it
 * exists in the player's equipment.
 *
 * **Return value:** true when every item were unequipped from equipment.
 */
static int entity_unequip_item(lua_State *s)
{
    Entity *ch = checkCharacter(s, 1);
    ItemClass *it = checkItemClass(s, 2);

    Inventory inv(ch);
    lua_pushboolean(s, inv.unequipItem(it->getDatabaseID()));
    return 1;
}

/** LUA_CATEGORY Character and being interaction (being)
 */

/** LUA chr_get_quest (being)
 * chr_get_quest(handle character, string name)
 **
 * **Return value:** The quest variable named ''name'' for the given character.
 *
 * **Warning:** May only be called from an NPC talk function.
 *
 */
static int chr_get_quest(lua_State *s)
{
    Entity *q = checkCharacter(s, 1);
    const char *name = luaL_checkstring(s, 2);
    luaL_argcheck(s, name[0] != 0, 2, "empty variable name");

    Script::Thread *thread = checkCurrentThread(s);

    std::string value;
    bool res = getQuestVar(q, name, value);
    if (res)
    {
        push(s, value);
        return 1;
    }
    QuestCallback *f = new QuestThreadCallback(&LuaScript::getQuestCallback,
                                               getScript(s));
    recoverQuestVar(q, name, f);

    thread->mState = Script::ThreadExpectingString;
    return lua_yield(s, 0);
}

/** LUA chr_set_quest (being)
 * chr_set_quest(handle character, string name, string value)
 **
 * Sets the quest variable named ''name'' for the given  character to the value
 * ''value''.
 */
static int chr_set_quest(lua_State *s)
{
    Entity *q = checkCharacter(s, 1);
    const char *name = luaL_checkstring(s, 2);
    const char *value = luaL_checkstring(s, 3);
    luaL_argcheck(s, name[0] != 0, 2, "empty variable name");

    setQuestVar(q, name, value);
    return 0;
}

/** LUA entity:set_ability_mana (being)
 * entity:set_ability_mana(int abilityid, int new_mana)
 * entity:set_ability_mana(string abilityname, int new_mana)
 **
 * Valid only for character entities.
 *
 * Sets the mana (recharge status) of the ability to a new value for the
 * character.
 *
 * **Note:** When passing the ''abilityname'' as parameter make sure that it is
 * formatted in this way: <setname>_<abilityname> (for eg. "Magic_Healingspell").
 */
static int entity_set_ability_mana(lua_State *s)
{
    Entity *c = checkCharacter(s, 1);
    auto *abilityInfo = checkAbility(s, 2);
    const int mana = luaL_checkint(s, 3);
    if (!c->getComponent<AbilityComponent>()->setAbilityMana(abilityInfo->id,
                                                             mana))
    {
        luaL_error(s,
                   "set_ability_mana called with ability "
                   "that is not owned by character.");
    }
    return 0;
}

/** LUA entity:ability_mana (being)
 * entity:ability_mana(int abilityid)
 * entity:ability_mana(string abilityname)
 **
 * **Return value:** The mana (recharge status) of the ability that is owned by
 * the character.
 *
 * **Note:** When passing the ''abilityname'' as parameter make sure that it is
 * formatted in this way: <setname>_<abilityname> (for eg. "Magic_Healingspell").
 */
static int entity_get_ability_mana(lua_State *s)
{
    Entity *c = checkCharacter(s, 1);
    auto *abilityComponent = c->getComponent<AbilityComponent>();
    auto *abilityInfo = checkAbility(s, 2);
    AbilityMap::iterator it = abilityComponent->findAbility(abilityInfo->id);
    luaL_argcheck(s, it != abilityComponent->getAbilities().end(), 2,
                  "character does not have ability");
    lua_pushinteger(s, it->second.currentPoints);
    return 1;
}

/** LUA entity:cooldown_ability (being)
 * entity:cooldown_ability(int abilityid)
 * entity:cooldown_ability(string abilityname)
 **
 * Starts the cooldown of the passed ability. No other ability will be useable
 * in this time.
 *
 * You do not need to call this if the attribute is set to ''autoconsume''.
 *
 * **Note:** When passing the ''abilityname'' as parameter make sure that it is
 * formatted in this way: <setname>_<abilityname> (for eg. "Magic_Healingspell").
 */
static int entity_cooldown_ability(lua_State *s)
{
    Entity *c = checkCharacter(s, 1);
    auto *abilityComponent = c->getComponent<AbilityComponent>();
    auto *abilityInfo = checkAbility(s, 2);
    abilityComponent->startCooldown(*c, abilityInfo);
    return 0;
}

/** LUA entity:walk (being)
 * entity:walk(int pixelX, int pixelY [, int walkSpeed])
 **
 * Valid only for being entities.
 *
 * Set the desired destination in pixels for the being.
 *
 * The optional **'WalkSpeed'** is to be given in tiles per second. The average
 * speed is 6.0 tiles per second. If no speed is given the default speed of the
 * being is used.
 */
static int entity_walk(lua_State *s)
{
    Entity *being = checkBeing(s, 1);
    const int x = luaL_checkint(s, 2);
    const int y = luaL_checkint(s, 3);

    auto *beingComponent = being->getComponent<BeingComponent>();

    beingComponent->setDestination(*being, Point(x, y));

    if (lua_gettop(s) >= 4)
    {
        const double speedTps = luaL_checknumber(s, 4);
        beingComponent->setAttribute(*being, ATTR_MOVE_SPEED_TPS, speedTps);
        const double modifiedSpeedTps =
                beingComponent->getModifiedAttribute(ATTR_MOVE_SPEED_TPS);
        beingComponent->setAttribute(*being, ATTR_MOVE_SPEED_RAW,
                                     utils::tpsToRawSpeed(modifiedSpeedTps));
    }

    return 0;
}

/** LUA entity:destination (being)
 * local x, y = entity:destination()
 **
 * Valid only for being entities.
 *
 * **Return value:** The x and y coordinates of the destination.
 */
static int entity_destination(lua_State *s)
{
    Entity *being = checkBeing(s, 1);
    auto *beingComponent = being->getComponent<BeingComponent>();
    const Point &point = beingComponent->getDestination();
    lua_pushinteger(s, point.x);
    lua_pushinteger(s, point.y);
    return 2;
}

/** LUA entity:heal (being)
 * entity:heal([int value])
 **
 * Valid only for being entities.
 *
 * Restores ''value'' lost hit points to the being. Value can be omitted to
 * restore the being to full hit points.
 *
 * While you can (ab)use this function to hurt a being by using a negative
 * value you should rather use entity:damage for this purpose.
 */
static int entity_heal(lua_State *s)
{
    Entity *being = checkBeing(s, 1);

    if (lua_gettop(s) == 1) // when there is only one argument
        being->getComponent<BeingComponent>()->heal(*being);
    else
        being->getComponent<BeingComponent>()->heal(*being, luaL_checkint(s, 2));

    return 0;
}

/** LUA entity:name (being)
 * entity:name()
 **
 * Valid only for being entities.
 *
 * **Return value:** Name of the being.
 */
static int entity_get_name(lua_State *s)
{
    Entity *being = checkBeing(s, 1);
    push(s, being->getComponent<BeingComponent>()->getName());
    return 1;
}

/** LUA entity:type (being)
 * entity:type()
 **
 * **Return value:** Type of the given entity. These type constants are defined
 * in libmana-constants.lua:
 *
 * | 0 | TYPE_ITEM      |
 * | 1 | TYPE_ACTOR     |
 * | 2 | TYPE_NPC       |
 * | 3 | TYPE_MONSTER   |
 * | 4 | TYPE_CHARACTER |
 * | 5 | TYPE_EFFECT    |
 * | 6 | TYPE_OTHER     |
*/
static int entity_get_type(lua_State *s)
{
    Entity *entity = LuaEntity::check(s, 1);
    lua_pushinteger(s, entity->getType());
    return 1;
}

/** LUA entity:action (being)
 * entity:action()
 **
 * Valid only for being entities.
 *
 * **Return value:** Current action of the being. These action constants are
 * defined in libmana-constants.lua:
 *
 * | 0 | ACTION_STAND  |
 * | 1 | ACTION_WALK   |
 * | 2 | ACTION_SIT    |
 * | 3 | ACTION_DEAD   |
 * | 4 | ACTION_HURT   |
 */
static int entity_get_action(lua_State *s)
{
    Entity *being = checkBeing(s, 1);
    lua_pushinteger(s, being->getComponent<BeingComponent>()->getAction());
    return 1;
}

/** LUA entity:set_action (being)
 * entity:set_action(int action)
 **
 * Valid only for being entities.
 *
 * Sets the current action for the being.
 */
static int entity_set_action(lua_State *s)
{
    Entity *being = checkBeing(s, 1);
    BeingAction act = static_cast<BeingAction>(luaL_checkint(s, 2));
    being->getComponent<BeingComponent>()->setAction(*being, act);
    return 0;
}

/** LUA entity:direction (being)
 * entity:direction()
 **
 * Valid only for being entities.
 *
 * **Return value:** Current direction of the being. These direction constants
 * are defined in libmana-constants.lua:
 *
 * | 0 | DIRECTION_DEFAULT |
 * | 1 | DIRECTION_UP      |
 * | 2 | DIRECTION_DOWN    |
 * | 3 | DIRECTION_LEFT    |
 * | 4 | DIRECTION_RIGHT   |
 * | 5 | DIRECTION_INVALID |
 */
static int entity_get_direction(lua_State *s)
{
    Entity *being = checkBeing(s, 1);
    lua_pushinteger(s, being->getComponent<BeingComponent>()->getDirection());
    return 1;
}

/** LUA entity:set_direction (being)
 * entity:set_direction(int direction)
 **
 * Valid only for being entities.
 *
 * Sets the current direction of the given being. Directions are same as in
 * ''entity:direction''.
 */
static int entity_set_direction(lua_State *s)
{
    Entity *being = checkBeing(s, 1);
    BeingDirection dir = static_cast<BeingDirection>(luaL_checkint(s, 2));
    being->getComponent<BeingComponent>()->setDirection(*being, dir);
    return 0;
}

/** LUA entity:set_walkmask (being)
 * entity:set_walkmask(string mask)
 **
 * Valid only for actor entities.
 *
 * Sets the walkmasks of an actor. The mask is a set of characters which stand
 * for different collision types.
 *
 * | w | Wall      |
 * | c | Character |
 * | m | Monster   |
 *
 * This means entity:set_walkmask("wm") will prevent the being from walking
 * over walls and monsters.
 */
static int entity_set_walkmask(lua_State *s)
{
   Entity *being = checkActor(s, 1);
   unsigned char walkmask = checkWalkMask(s, 2);
   being->getComponent<ActorComponent>()->setWalkMask(walkmask);
   return 0;
}

/** LUA entity:walkmask (being)
 * entity:walkmask()
 **
 * Valid only for actor entities.
 *
 * **Return value:** The walkmask of the actor formatted as string. (See
 * [[scripting#entityset_walkmask|entity:set_walkmask]])
 */
static int entity_get_walkmask(lua_State *s)
{
   Entity *being = checkBeing(s, 1);
   const unsigned char mask =
           being->getComponent<ActorComponent>()->getWalkMask();
   luaL_Buffer buffer;
   luaL_buffinit(s, &buffer);
   if (mask & Map::BLOCKMASK_WALL)
       luaL_addstring(&buffer, "w");
   if (mask & Map::BLOCKMASK_CHARACTER)
       luaL_addstring(&buffer, "c");
   if (mask & Map::BLOCKMASK_MONSTER)
       luaL_addstring(&buffer, "m");
   luaL_pushresult(&buffer);
   return 1;
}

/** LUA entity:warp (being)
 * entity:warp(int mapID, int posX, int posY)
 * entity:warp(string mapName, int posX, int posY)
 **
 * Valid only for character entities.
 *
 * Teleports the character to the position ''posX'':''posY'' on the map
 * with the ID number ''mapID'' or name ''mapName''. The ''mapID'' can be
 * substituted by ''nil'' to warp the character to a new position on the
 * current map.
 */
static int entity_warp(lua_State *s)
{
    Entity *character = checkCharacter(s, 1);
    int x = luaL_checkint(s, 3);
    int y = luaL_checkint(s, 4);

    bool b = lua_isnil(s, 2);
    if (!(b || lua_isnumber(s, 2) || lua_isstring(s, 2)))
    {
        luaL_error(s, "warp called with incorrect parameters.");
        return 0;
    }
    MapComposite *m;
    if (b)
    {
        m = checkCurrentMap(s);
    }
    else if (lua_isnumber(s, 2))
    {
        m = MapManager::getMap(lua_tointeger(s, 2));
        luaL_argcheck(s, m, 2, "invalid map id");
    }
    else
    {
        m = MapManager::getMap(lua_tostring(s, 2));
        luaL_argcheck(s, m, 2, "invalid map name");
    }

    Map *map = m->getMap();

    // If the wanted warp place is unwalkable
    if (!map->getWalk(x / map->getTileWidth(), y / map->getTileHeight()))
    {
        int c = 50;
        LOG_INFO("warp called with a non-walkable place.");
        do
        {
            x = rand() % map->getWidth();
            y = rand() % map->getHeight();
        } while (!map->getWalk(x, y) && --c);
        x *= map->getTileWidth();
        y *= map->getTileHeight();
    }
    GameState::enqueueWarp(character, m, Point(x, y));

    return 0;
}

/** LUA entity:position (being)
 * entity:position()
 **
 * Valid only for actor entities.
 *
 * **Return value:** The x and y position of the actor in pixels, measured from
 * the top-left corner of the map it is currently on.
 */
static int entity_get_position(lua_State *s)
{
    Entity *being = checkActor(s, 1);
    const Point &p = being->getComponent<ActorComponent>()->getPosition();
    lua_pushinteger(s, p.x);
    lua_pushinteger(s, p.y);
    return 2;
}

/** LUA entity:x (being)
 * entity:x()
 **
 * Valid only for actor entities.
 *
 * **Return value:** The x position of the actor in pixels, measured from
 * the left border of the map it is currently on.
 */
static int entity_get_x(lua_State *s)
{
    Entity *being = checkActor(s, 1);
    const Point &p = being->getComponent<ActorComponent>()->getPosition();
    lua_pushinteger(s, p.x);
    return 1;
}

/** LUA entity:y (being)
 * entity:y()
 **
 * Valid only for actor entities.
 *
 * **Return value:** The y position of the actor in pixels, measured from
 * the top border of the map it is currently on.
 */
static int entity_get_y(lua_State *s)
{
    Entity *being = checkActor(s, 1);
    const Point &p = being->getComponent<ActorComponent>()->getPosition();
    lua_pushinteger(s, p.y);
    return 1;
}

/** LUA entity:base_attribute (being)
 * entity:base_attribute(int attribute_id)
 **
 * Valid only for being entities.
 *
 * **Return value:** Returns the value of the being's ''base attribute''.
 */
static int entity_get_base_attribute(lua_State *s)
{
    Entity *being = checkBeing(s, 1);
    int attr = luaL_checkint(s, 2);
    luaL_argcheck(s, attr > 0, 2, "invalid attribute id");

    lua_pushinteger(s, being->getComponent<BeingComponent>()->getAttributeBase(attr));
    return 1;
}

/** LUA entity:set_base_attribute (being)
 * entity:set_base_attribute(int attribute_id, double new_value)
 **
 * Valid only for being entities.
 *
 * Set the value of the being's ''base attribute'' to the 'new_value' parameter
 * given. (It can be negative).
 */
static int entity_set_base_attribute(lua_State *s)
{
    Entity *being = checkBeing(s, 1);
    int attr = luaL_checkint(s, 2);
    double value = luaL_checknumber(s, 3);

    being->getComponent<BeingComponent>()->setAttribute(*being, attr, value);
    return 0;
}

/** entity:modified_attribute (being)
 * entity:modified_attribute(int attribute_id)
 **
 * Valid only for being entities.
 *
 * *Return value:** Returns the value of the being's ''modified attribute''.
 *
 * The modified attribute is equal to the base attribute + currently applied
 * modifiers.
 *
 * To get to know how to configure and create modifiers, you can have a look at
 * the [[attributes.xml]] file and at the [[#entityapply_attribute_modifier]]()
 * and [[#entityremove_attribute_modifier]]() lua functions.
 *
 * Note also that items, equipment, and monsters attacks can cause attribute
 * modifiers.
 *
 * FIXME: This functions about applying and removing modifiers are still WIP,
 * because some simplifications and renaming could occur.
 */
static int entity_get_modified_attribute(lua_State *s)
{
    Entity *being = checkBeing(s, 1);
    int attr = luaL_checkint(s, 2);
    luaL_argcheck(s, attr > 0, 2, "invalid attribute id");

    const double value =
            being->getComponent<BeingComponent>()->getModifiedAttribute(attr);
    lua_pushinteger(s, value);
    return 1;
}

/** LUA entity:apply_attribute_modifier (being)
 * entity:apply_attribute_modifier(int attribute_id, double value,
 *                                 unsigned int layer, [unsigned short duration,
 *                                 [unsigned int effect_id]])
 **
 * Valid only for being entities.
 *
 * **Parameters description:** \\
 *   * **value** (double): The modifier value (can be negative).
 *   * **layer** (unsigned int): The layer or level of the modifier.
 *     As modifiers are stacked on an attribute, the layer determines
 *     where the modifier will be inserted. Also, when adding a modifier,
 *     all the modifiers with an higher ayer value will also be recalculated.
 *   * **duration** (unsigned short): The modifier duration in ticks((A tick is
 *     equal to 100ms.)). If set to 0, the modifier is permanent.
 *   * **effect_id** (unsigned int): Set and keep that parameter when you want
 *     to retrieve the exact layer later. (FIXME: Check this.)
 */
static int entity_apply_attribute_modifier(lua_State *s)
{
    Entity *being   = checkBeing(s, 1);
    int attr        = luaL_checkint(s,2);
    double value    = luaL_checknumber(s, 3);
    int layer       = luaL_checkint(s, 4);
    int duration    = luaL_optint(s, 5, 0);
    int effectId    = luaL_optint(s, 6, 0);

    being->getComponent<BeingComponent>()->applyModifier(*being, attr, value,
                                                         layer, duration,
                                                         effectId);
    return 0;
}

/** LUA entity:remove_attribute_modifier (being)
 * entity:remove_attribute_modifier(int attribute_id,
 *                                  double value, unsigned int layer)
 **
 * Valid only for being entities.
 *
 * Permits to remove an attribute modifier by giving its value and its layer.
 */
static int entity_remove_attribute_modifier(lua_State *s)
{
    Entity *being   = checkBeing(s, 1);
    int attr        = luaL_checkint(s, 2);
    double value    = luaL_checknumber(s, 3);
    int layer       = luaL_checkint(s, 4);
    int effectId    = luaL_optint(s, 5, 0);

    being->getComponent<BeingComponent>()->removeModifier(*being, attr, value,
                                                          layer, effectId);
    return 0;
}

/** LUA entity:gender (being)
 * entity:gender()
 **
 * Valid only for being entities.
 *
 * **Return value:** The gender of the being. These gender constants are
 * defined in libmana-constants.lua:
 *
 * | 0 | GENDER_MALE        |
 * | 1 | GENDER_FEMALE      |
 * | 2 | GENDER_UNSPECIFIED |
 */
static int entity_get_gender(lua_State *s)
{
    Entity *b = checkBeing(s, 1);
    lua_pushinteger(s, b->getComponent<BeingComponent>()->getGender());
    return 1;
}

/** LUA entity:set_gender (being)
 * entity:set_gender(int gender)
 **
 * Valid only for being entities.
 *
 * Sets the gender of the being.
 *
 * The gender constants are defined in libmana-constants.lua:
 *
 * | 0 | GENDER_MALE        |
 * | 1 | GENDER_FEMALE      |
 * | 2 | GENDER_UNSPECIFIED |
 */
static int entity_set_gender(lua_State *s)
{
    Entity *b = checkBeing(s, 1);
    const int gender = luaL_checkinteger(s, 2);
    b->getComponent<BeingComponent>()->setGender(getGender(gender));
    return 0;
}

/** LUA entity:level (being)
 * entity:level()
 * entity:level(int skill_id)
 * entity:level(string skill_name)
 **
 * Valid only for character entities.
 *
 * **Return value:** Returns the level of the character. If a skill is passed
 * (either by name or id) the level of this skill is returned.
 *
 * **Note:** If the skill is provided as string (''skill_name'') you have to
 * use this format: <setname>_<skillname>. So for example: "Weapons_Unarmed".
 */
static int entity_get_level(lua_State *s)
{
    Entity *ch = checkCharacter(s, 1);
    auto *characterComponent = ch->getComponent<CharacterComponent>();
    if (lua_gettop(s) > 1)
    {
        int skillId = checkSkill(s, 2);
        lua_pushinteger(s, characterComponent->levelForExp(
                characterComponent->getExperience(skillId)));
    }
    else
    {
        lua_pushinteger(s, characterComponent->getLevel());
    }
    return 1;
}

/** LUA entity:xp (being)
 * entity:xp(int skill_id)
 * entity:xp(string skill_name)
 **
 * Valid only for character entities.
 *
 * **Return value:** The total experience collected by the character in
 * ''skill''.
 *
 * If the skill is provided as string (''skillname'') you have to use this
 * format: <setname>_<skillname>. So for example: "Weapons_Unarmed".
 */
static int entity_get_xp(lua_State *s)
{
    Entity *c = checkCharacter(s, 1);
    int skill = checkSkill(s, 2);
    const int exp = c->getComponent<CharacterComponent>()->getExperience(skill);

    lua_pushinteger(s, exp);
    return 1;
}

/** LUA entity:give_xp (being)
 * entity:give_xp(int skill, int amount [, int optimalLevel])
 * entity:give_xp(string skillname, int amount [, int optimalLevel])
 **
 * Valid only for character entities.
 *
 * Gives the character ''amount'' experience in skill ''skill''. When an
 * optimal level is set (over 0), the experience is reduced when the characters
 * skill level is beyond this. If the skill is provided as string
 * (''skillname'') you have to use this format: <setname>_<skillname>.
 * So for example: "Weapons_Unarmed".
 */
static int entity_give_xp(lua_State *s)
{
    Entity *c = checkCharacter(s, 1);
    int skill = checkSkill(s, 2);
    const int exp = luaL_checkint(s, 3);
    const int optimalLevel = luaL_optint(s, 4, 0);

    c->getComponent<CharacterComponent>()->receiveExperience(skill, exp,
                                                             optimalLevel);
    return 0;
}

/** LUA xp_for_level (being)
 * xp_for_level(int level)
 **
 * **Return value:** Returns the total experience necessary (counted from
 * level 0) for reaching ''level'' in any skill.
 */
static int xp_for_level(lua_State *s)
{
    const int level = luaL_checkint(s, 1);
    lua_pushinteger(s, CharacterComponent::expForLevel(level));
    return 1;
}

/** LUA entity:add_hit_taken (being)
 * add_hit_taken(int damage)
 **
 * Adds a damage value to the taken hits of a being. This list will be send to
 * all clients in the view range in order to allow to display the hit particles.
 */
static int entity_add_hit_taken(lua_State *s)
{
    Entity *c = checkBeing(s, 1);
    const int damage = luaL_checkinteger(s, 2);
    c->getComponent<BeingComponent>()->addHitTaken(damage);
    return 0;
}

/** LUA entity:hair_color (being)
 * entity:hair_color()
 **
 * Valid only for character entities.
 *
 * **Return value:** The hair color ID of the character.
 */
static int entity_get_hair_color(lua_State *s)
{
    Entity *c = checkCharacter(s, 1);

    lua_pushinteger(s, c->getComponent<CharacterComponent>()->getHairColor());
    return 1;
}

/** LUA entity:set_hair_color (being)
 * entity:set_hair_color(int color)
 **
 * Valid only for character entities.
 *
 * Sets the hair color ID of the character to ''color''.
 */
static int entity_set_hair_color(lua_State *s)
{
    Entity *c = checkCharacter(s, 1);
    const int color = luaL_checkint(s, 2);
    luaL_argcheck(s, color >= 0, 2, "invalid color id");

    c->getComponent<CharacterComponent>()->setHairColor(color);
    c->getComponent<ActorComponent>()->raiseUpdateFlags(
            UPDATEFLAG_LOOKSCHANGE);

    return 0;
}

/** LUA entity:hair_style (being)
 * entity:hair_style()
 **
 * Valid only for character entities.
 *
 * **Return value:** The hair style ID of the character.
 */
static int entity_get_hair_style(lua_State *s)
{
    Entity *c = checkCharacter(s, 1);

    lua_pushinteger(s, c->getComponent<CharacterComponent>()->getHairStyle());
    return 1;
}

/** LUA entity:set_hair_style (being)
 * entity:set_hair_style(int style)
 **
 * Valid only for character entities.
 *
 * Sets the hair style ID of the character to ''style''.
 */
static int entity_set_hair_style(lua_State *s)
{
    Entity *c = checkCharacter(s, 1);
    const int style = luaL_checkint(s, 2);
    luaL_argcheck(s, style >= 0, 2, "invalid style id");

    c->getComponent<CharacterComponent>()->setHairStyle(style);
    c->getComponent<ActorComponent>()->raiseUpdateFlags(
            UPDATEFLAG_LOOKSCHANGE);
    return 0;
}

/** LUA entity:kill_count (being)
 * entity:kill_count(int monsterId)
 * entity:kill_count(string monsterName)
 * entity:kill_count(MonsterClass monsterClass)
 **
 * Valid only for character entities.
 *
 * **Return value:** The total number of monsters of the specy (passed either
 * as monster id, monster name or monster class) the character has killed
 * during its career.
 */
static int entity_get_kill_count(lua_State *s)
{
    Entity *c = checkCharacter(s, 1);
    MonsterClass *monster = checkMonsterClass(s, 2);

    lua_pushinteger(s, c->getComponent<CharacterComponent>()->getKillCount(monster->getId()));
    return 1;
}

/** LUA entity:rights (being)
 * entity:rights()
 **
 * Valid only for character entities.
 *
 * **Return value:** The access level of the account of the character.
 */
static int entity_get_rights(lua_State *s)
{
    Entity *c = checkCharacter(s, 1);
    lua_pushinteger(s, c->getComponent<CharacterComponent>()->getAccountLevel());
    return 1;
}

/** LUA entity:kick (being)
 * entity:kick()
 **
 * Valid only for character entities.
 *
 * Kicks the character.
 */
static int entity_kick(lua_State *s)
{
    Entity *ch = checkCharacter(s, 1);
    MessageOut kickmsg(GPMSG_CONNECT_RESPONSE);
    kickmsg.writeInt8(ERRMSG_ADMINISTRATIVE_LOGOFF);
    ch->getComponent<CharacterComponent>()->getClient()->disconnect(kickmsg);
    return 0;
}

/** LUA entity:mapid (being)
 * entity:mapid()
 **
 * **Return value:** the id of the map where the entity is located or nil if
 * there is none.
 */
static int entity_get_mapid(lua_State *s)
{
    Entity *entity = LuaEntity::check(s, 1);
    if (MapComposite *map = entity->getMap())
        lua_pushinteger(s, map->getID());
    else
        lua_pushnil(s);

    return 1;
}

/** LUA chr_request_quest (being)
 * chr_request_quest(handle character, string questvariable, Ref function)
 **
 * Requests the questvar from the account server. This will make it available in
 * the quest cache after some time. The passed function will be called back as
 * soon the quest var is available.
 */
static int chr_request_quest(lua_State *s)
{
    Entity *ch = checkCharacter(s, 1);
    const char *name = luaL_checkstring(s, 2);
    luaL_argcheck(s, name[0] != 0, 2, "empty variable name");
    luaL_checktype(s, 3, LUA_TFUNCTION);

    std::string value;
    bool res = getQuestVar(ch, name, value);
    if (res)
    {
        // Already cached, call passed callback immediately
        Script *script = getScript(s);
        Script::Ref callback;
        script->assignCallback(callback);

        script->prepare(callback);
        script->push(ch);
        script->push(name);
        script->push(value);
        script->execute(ch->getMap());

        return 0;
    }

    QuestCallback *f = new QuestRefCallback(getScript(s), name);
    recoverQuestVar(ch, name, f);

    return 0;
}

/** LUA chr_try_get_quest (being)
 * chr_try_get_quest(handle character, string questvariable)
 **
 * Callback for checking if a quest variable is available in cache.
 *
 * **Return value:** It will return the variable if it is or nil
 * if it is not in cache.
 */
static int chr_try_get_quest(lua_State *s)
{
    Entity *q = checkCharacter(s, 1);
    const char *name = luaL_checkstring(s, 2);
    luaL_argcheck(s, name[0] != 0, 2, "empty variable name");

    std::string value;
    bool res = getQuestVar(q, name, value);
    if (res)
        push(s, value);
    else
        lua_pushnil(s);
    return 1;
}

/** LUA get_character_by_name (being)
 * get_character_by_name(string name)
 **
 * Tries to find an online character by name.
 *
 * **Return value** the character handle or nil if there is none.
 */
static int get_character_by_name(lua_State *s)
{
    const char *name = luaL_checkstring(s, 1);
    push(s, gameHandler->getCharacterByNameSlow(name));
    return 1;
}

/** LUA chr_get_post (being)
 * chr_get_post(handle character)
 **
 * Gets the post for the character.
 */
static int chr_get_post(lua_State *s)
{
    Entity *c = checkCharacter(s, 1);

    Script *script = getScript(s);
    Script::Thread *thread = checkCurrentThread(s, script);

    PostCallback f = { &LuaScript::getPostCallback, script };
    postMan->getPost(c, f);

    thread->mState = Script::ThreadExpectingTwoStrings;
    return lua_yield(s, 0);
}

/** LUA entity:register (being)
 * entity:register()
 **
 * Makes the server call the on_being_death and on_entity_remove callbacks
 * when the being dies or the entity is removed from the map.
 *
 * **Note:** You should never need to call this in most situations. It is
 * handeled by the libmana.lua
 */
static int entity_register(lua_State *s)
{
    Entity *entity = LuaEntity::check(s, 1);
    Script *script = getScript(s);

    entity->signal_removed.connect(sigc::mem_fun(script, &Script::processRemoveEvent));

    if (BeingComponent *bc = entity->findComponent<BeingComponent>())
        bc->signal_died.connect(sigc::mem_fun(script, &Script::processDeathEvent));

    return 0;
}

/** LUA entity:shake_screen (being)
 * entity:shake_screen(int x, int y[, float strength, int radius])
 **
 * Valid only for character entities.
 *
 * Shakes the screen for a given character.
 */
static int entity_shake_screen(lua_State *s)
{
    Entity *c = checkCharacter(s, 1);
    const int x = luaL_checkint(s, 2);
    const int y = luaL_checkint(s, 3);

    MessageOut msg(GPMSG_SHAKE);
    msg.writeInt16(x);
    msg.writeInt16(y);

    if (lua_isnumber(s, 4))
        msg.writeInt16((int) (lua_tonumber(s, 4) * 10000));
    if (lua_isnumber(s, 5))
        msg.writeInt16(lua_tointeger(s, 5));

    c->getComponent<CharacterComponent>()->getClient()->send(msg);

    return 0;
}

/** LUA entity:show_text_particle (being)
 * entity:show_text_particle(string text)
 **
 * Valid only for character entities.
 *
 * Shows a text particle on a client. This effect is only visible for the
 * character.
 */
static int entity_show_text_particle(lua_State *s)
{
    Entity *c = checkCharacter(s, 1);
    const char *text = luaL_checkstring(s, 2);

    MessageOut msg(GPMSG_CREATE_TEXT_PARTICLE);
    msg.writeString(text);
    c->getComponent<CharacterComponent>()->getClient()->send(msg);

    return 0;
}

/** LUA entity:give_ability (being)
 * entity:give_ability(int ability)
 **
 * Valid only for character and monster entities.
 *
 * Enables a ability for a character.
 */
static int entity_give_ability(lua_State *s)
{
    // cost_type is ignored until we have more than one cost type
    Entity *b = checkBeing(s, 1);
    auto *abilityInfo = checkAbility(s, 2);
    const int currentMana = luaL_optint(s, 3, 0);

    b->getComponent<AbilityComponent>()->giveAbility(abilityInfo->id,
                                                     currentMana);
    return 0;
}

/** LUA entity:has_ability (being)
 * entity:has_ability(int ability)
 **
 * Valid only for character and monster entities.
 *
 * **Return value:** True if the character has the ability, false otherwise.
 */
static int entity_has_ability(lua_State *s)
{
    Entity *b = checkBeing(s, 1);
    const int ability = luaL_checkint(s, 2);

    lua_pushboolean(s, b->getComponent<AbilityComponent>()->hasAbility(ability));
    return 1;
}

/** LUA entity:take_ability (being)
 * entity:take_ability(int ability)
 **
 * Valid only for character and monster entities.
 *
 * Removes a ability from a entity.
 *
 * **Return value:** True if removal was successful, false otherwise (in case
 * the character did not have the ability).
 */
static int entity_take_ability(lua_State *s)
{
    Entity *b = checkBeing(s, 1);
    const int ability = luaL_checkint(s, 2);

    auto *abilityComponent = b->getComponent<AbilityComponent>();
    lua_pushboolean(s, abilityComponent->hasAbility(ability));
    abilityComponent->takeAbility(ability);
    return 1;
}

/** LUA entity:use_ability (being)
 * entity:use_ability(int ability)
 **
 * Valid only for character and monster entities.
 *
 * Makes the entity using the given ability if it is available and recharged.
 *
 * **Return value:** True if the ability was used successfully. False otherwise
 * (if the ability is not available for the entity or was not recharged).
 */
static int entity_use_ability(lua_State *s)
{
    Entity *b = checkBeing(s, 1);
    const int ability = luaL_checkint(s, 2);
    bool targetIsBeing = lua_gettop(s) == 3;

    auto *abilityComponent = b->getComponent<AbilityComponent>();
    if (targetIsBeing)
    {
        Entity *target = checkBeing(s, 3);
        lua_pushboolean(s, abilityComponent->useAbilityOnBeing(*b, ability,
                                                               target));
    }
    else
    {
        const int x = luaL_checkint(s, 3);
        const int y = luaL_checkint(s, 4);
        lua_pushboolean(s, abilityComponent->useAbilityOnPoint(*b, ability,
                                                               x, y));
    }

    return 1;
}


/** LUA_CATEGORY Monster (monster)
 */

/** LUA entity:monster_id (monster)
 * entity:monster_id()
 **
 * Valid only for monster entities.
 *
 * **Return value:** The id of the monster class.
 */
static int entity_get_monster_id(lua_State *s)
{
    Entity *monster = checkMonster(s, 1);
    MonsterComponent *monsterComponent = monster->getComponent<MonsterComponent>();
    lua_pushinteger(s, monsterComponent->getSpecy()->getId());
    return 1;
}


/** LUA_CATEGORY Status effects (statuseffects)
 */

/** LUA entity:apply_status (statuseffects)
 * entity:apply_status(int status_id, int time)
 **
 * Valid only for being entities.
 *
 * Gives a being a status effect ''status_id'', status effects don't work on
 * NPCs. ''time'' is in game ticks.
 */
static int entity_apply_status(lua_State *s)
{
    Entity *being = checkBeing(s, 1);
    const int id = luaL_checkint(s, 2);
    const int time = luaL_checkint(s, 3);

    being->getComponent<BeingComponent>()->applyStatusEffect(id, time);
    return 0;
}

/** LUA entity:remove_status (statuseffects)
 * entity:remove_status(int status_id)
 **
 * Valid only for being entities.
 *
 * Removes a given status effect from a being.
 */
static int entity_remove_status(lua_State *s)
{
    Entity *being = checkBeing(s, 1);
    const int id = luaL_checkint(s, 2);

    being->getComponent<BeingComponent>()->removeStatusEffect(id);
    return 0;
}

/** LUA entity:has_status (statuseffects)
 * entity:has_status(int status_id)
 **
 * Valid only for being entities.
 *
 * **Return value:** True if the being has a given status effect.
 */
static int entity_has_status(lua_State *s)
{
    Entity *being = checkBeing(s, 1);
    const int id = luaL_checkint(s, 2);

    lua_pushboolean(s, being->getComponent<BeingComponent>()->hasStatusEffect(id));
    return 1;
}

/** LUA entity:status_time (statuseffects)
 * entity:status_time(int status_id)
 **
 * Valid only for being entities.
 *
 * **Return Value:** Number of ticks remaining on a status effect.
 */
static int entity_get_status_time(lua_State *s)
{
    Entity *being = checkBeing(s, 1);
    const int id = luaL_checkint(s, 2);

    lua_pushinteger(s, being->getComponent<BeingComponent>()->getStatusEffectTime(id));
    return 1;
}

/** LUA entity:set_status_time (statuseffects)
 * entity:set_status_time(int status_id, int time)
 **
 * Valid only for being entities.
 *
 * Sets the time on a status effect a target being already has.
 */
static int entity_set_status_time(lua_State *s)
{
    Entity *being = checkBeing(s, 1);
    const int id = luaL_checkint(s, 2);
    const int time = luaL_checkint(s, 3);

    being->getComponent<BeingComponent>()->setStatusEffectTime(id, time);
    return 0;
}


/** LUA_CATEGORY Map information (mapinformation)
 */

/** LUA get_map_id (mapinformation)
 * get_map_id()
 **
 * **Return value:** The ID number of the map the script runs on.
 */
static int get_map_id(lua_State *s)
{
    Script *script = getScript(s);

    if (MapComposite *mapComposite = script->getContext()->map)
        lua_pushinteger(s, mapComposite->getID());
    else
        lua_pushnil(s);

    return 1;
}

/** LUA get_map_property (mapinformation)
 * get_map_property(string key)
 **
 * **Return value:** The value of the property ''key'' of the current map. The
 * string is empty if the property ''key'' does not exist.
 */
static int get_map_property(lua_State *s)
{
    const char *property = luaL_checkstring(s, 1);
    Map *map = checkCurrentMap(s)->getMap();

    push(s, map->getProperty(property));
    return 1;
}

/** LUA is_walkable (mapinformation)
 * is_walkable(int x, int y)
 **
 * **Return value:** True if ''x'':''y'' is a walkable pixel
 * on the current map.
 */
static int is_walkable(lua_State *s)
{
    const int x = luaL_checkint(s, 1);
    const int y = luaL_checkint(s, 2);
    Map *map = checkCurrentMap(s)->getMap();

    // If the wanted warp place is unwalkable
    if (map->getWalk(x / map->getTileWidth(), y / map->getTileHeight()))
        lua_pushboolean(s, 1);
    else
        lua_pushboolean(s, 0);

    return 1;
}

/** LUA get_path_length (mapinformation)
 * get_path_lenght(int startX, int startY, int destX, int destY, int maxRange)
 * get_path_lenght(int startX, int startY, int destX, int destY, int maxRange,
 *                 string walkmask)
 **
 * Tries to find a path from the start coordinates to the target ones with a
 * maximum of ''maxRange'' steps (in tiles).
 *
 * If no ''walkmask'' is passed '''w''' is used.
 *
 * **Return value:** The number of steps (in tiles) are required to reach
 * the target or 0 if no path was found.
 */
static int get_path_length(lua_State *s)
{
    const int startX = luaL_checkint(s, 1);
    const int startY = luaL_checkint(s, 2);
    const int destX = luaL_checkint(s, 3);
    const int destY = luaL_checkint(s, 4);
    unsigned maxRange = luaL_checkint(s, 5);
    unsigned char walkmask = BLOCKTYPE_WALL;
    if (lua_gettop(s) > 5)
        walkmask = checkWalkMask(s, 6);

    Map *map = checkCurrentMap(s)->getMap();
    Path path = map->findPath(startX / map->getTileWidth(),
                              startY / map->getTileHeight(),
                              destX / map->getTileWidth(),
                              destY / map->getTileHeight(),
                              walkmask, maxRange);
    lua_pushinteger(s, path.size());
    return 1;
}

/** LUA map_get_pvp (mapinformation)
 * map_get_pvp()
 **
 * **Return value:** The pvp situation of the map.
 *
 * There are constants for the different pvp situations in the libmana-constants.lua:
 *
 * | 0 | PVP_NONE  |
 * | 1 | PVP_FREE  |
 */
static int map_get_pvp(lua_State *s)
{
    MapComposite *m = checkCurrentMap(s);
    lua_pushinteger(s, m->getPvP());
    return 1;
}


/** LUA_CATEGORY Persistent variables (variables)
 */

/** LUA on_mapvar_changed (variables)
 * on_mapvar_changed(string key, function func)
 **
 * Registers a callback to the key. This callback will be called with the key
 * and value of the changed variable.
 *
 * **Example:**
 * <code lua>on_mapvar_changed(key, function(key, value)
 *   log(LOG_DEBUG, "mapvar " .. key .. " has new value " .. value)
 * end)</code>
 */
static int on_mapvar_changed(lua_State *s)
{
    const char *key = luaL_checkstring(s, 1);
    luaL_checktype(s, 2, LUA_TFUNCTION);
    luaL_argcheck(s, key[0] != 0, 2, "empty variable name");
    MapComposite *m = checkCurrentMap(s);
    m->setMapVariableCallback(key, getScript(s));
    return 0;
}

/** LUA on_worldvar_changed (variables)
 * on_worldvar_changed(string key, function func)
 **
 * Registers a callback to the key. This callback will be called with the key
 * and value of the changed variable.
 *
 * **Example:**
 * <code lua>on_worldvar_changed(key, function(key, value)
 *   log(LOG_DEBUG, "worldvar " .. key .. " has new value " .. value)
 * end)</code>
 */
static int on_worldvar_changed(lua_State *s)
{
    const char *key = luaL_checkstring(s, 1);
    luaL_checktype(s, 2, LUA_TFUNCTION);
    luaL_argcheck(s, key[0] != 0, 2, "empty variable name");
    MapComposite *m = checkCurrentMap(s);
    m->setWorldVariableCallback(key, getScript(s));
    return 0;
}

/** LUA getvar_map (variables)
 * getvar_map(string variablename)
 **
 * **Return value:** the value of a persistent map variable.
 *
 * **See:** [[scripting#map|map[]]] for an easier way to get a map variable.
 */
static int getvar_map(lua_State *s)
{
    const char *name = luaL_checkstring(s, 1);
    luaL_argcheck(s, name[0] != 0, 1, "empty variable name");

    MapComposite *map = checkCurrentMap(s);

    push(s, map->getVariable(name));
    return 1;
}

/** LUA setvar_map (variables)
 * setvar_map(string variablename, string value)
 **
 * Sets the value of a persistent map variable.
 *
 * **See:** [[scripting#map|map[]]] for an easier way to get a map variable.
 */
static int setvar_map(lua_State *s)
{
    const char *name = luaL_checkstring(s, 1);
    const char *value = luaL_checkstring(s, 2);
    luaL_argcheck(s, name[0] != 0, 1, "empty variable name");

    MapComposite *map = checkCurrentMap(s);
    map->setVariable(name, value);

    return 0;
}

/** LUA getvar_world (variables)
 * getvar_world(string variablename)
 **
 * Gets the value of a persistent global variable.
 *
 * **See:** [[scripting#world|world[]]] for an easier way to get a map variable.
 */
static int getvar_world(lua_State *s)
{
    const char *name = luaL_checkstring(s, 1);
    luaL_argcheck(s, name[0] != 0, 1, "empty variable name");

    push(s, GameState::getVariable(name));
    return 1;
}

/** LUA setvar_world (variables)
 * setvar_world(string variablename, string value)
 **
 * Sets the value of a persistent global variable.
 *
 * **See:** [[scripting#world|world[]]] for an easier way to get a map variable.
 */
static int setvar_world(lua_State *s)
{
    const char *name = luaL_checkstring(s, 1);
    const char *value = luaL_checkstring(s, 2);
    luaL_argcheck(s, name[0] != 0, 1, "empty variable name");

    GameState::setVariable(name, value);
    return 0;
}


/** LUA_CATEGORY Logging (logging)
 */

/** LUA log (logging)
 * log(int log_level, string message)
 **
 * Log something at the specified log level. The available log levels are:
 * | 0 | LOG_FATAL    |
 * | 1 | LOG_ERROR    |
 * | 2 | LOG_WARNING  |
 * | 3 | LOG_INFO     |
 * | 4 | LOG_DEBUG    |
 */
static int log(lua_State *s)
{
    using utils::Logger;

    const int loglevel = luaL_checkint(s, 1);
    luaL_argcheck(s,
                  loglevel >= Logger::Fatal && loglevel <= Logger::Debug,
                  1,
                  "invalid log level");

    const std::string message = luaL_checkstring(s, 2);

    Logger::output(message, (Logger::Level) loglevel);
    return 0;
}


/** LUA_CATEGORY Area of Effect (area)
 * In order to easily use area of effects in your items or in your scripts,
 * the following functions are available:
 */

/** LUA get_beings_in_circle (area)
 * get_beings_in_circle(int x, int y, int radius)
 * get_beings_in_circle(handle actor, int radius)
 **
 * **Return value:** This function returns a lua table of all beings in a
 * circle of radius (in pixels) ''radius'' centered either at the pixel at
 * (''x'', ''y'') or at the position of ''being''.
 */
static int get_beings_in_circle(lua_State *s)
{
    int x, y, r;
    if (lua_isuserdata(s, 1))
    {
        Entity *b = checkActor(s, 1);
        const Point &pos = b->getComponent<ActorComponent>()->getPosition();
        x = pos.x;
        y = pos.y;
        r = luaL_checkint(s, 2);
    }
    else
    {
        x = luaL_checkint(s, 1);
        y = luaL_checkint(s, 2);
        r = luaL_checkint(s, 3);
    }

    MapComposite *m = checkCurrentMap(s);

    //create a lua table with the beings in the given area.
    lua_newtable(s);
    int tableStackPosition = lua_gettop(s);
    int tableIndex = 1;
    for (BeingIterator i(m->getAroundPointIterator(Point(x, y), r)); i; ++i)
    {
        Entity *b = *i;
        char t = b->getType();
        if (t == OBJECT_NPC || t == OBJECT_CHARACTER || t == OBJECT_MONSTER)
        {
            auto *actorComponent = b->getComponent<ActorComponent>();
            if (Collision::circleWithCircle(actorComponent->getPosition(),
                                            actorComponent->getSize(),
                                            Point(x, y), r))
            {
                push(s, b);
                lua_rawseti(s, tableStackPosition, tableIndex);
                tableIndex++;
            }
        }
    }

    return 1;
}

/** LUA get_beings_in_rectangle (area)
 * get_beings_in_rectangle(int x, int y, int width, int height)
 **
 * **Return value:** An table of being entities within the rectangle.
 * All parameters have to be passed as pixels.
 */
static int get_beings_in_rectangle(lua_State *s)
{
    const int x = luaL_checkint(s, 1);
    const int y = luaL_checkint(s, 2);
    const int w = luaL_checkint(s, 3);
    const int h = luaL_checkint(s, 4);

    MapComposite *m = checkCurrentMap(s);

    //create a lua table with the beings in the given area.
    lua_newtable(s);
    int tableStackPosition = lua_gettop(s);
    int tableIndex = 1;
    Rectangle rect = {x, y ,w, h};
    for (BeingIterator i(m->getInsideRectangleIterator(rect)); i; ++i)
    {
        Entity *b = *i;
        char t = b->getType();
        if ((t == OBJECT_NPC || t == OBJECT_CHARACTER || t == OBJECT_MONSTER) &&
            rect.contains(b->getComponent<ActorComponent>()->getPosition()))
        {
            push(s, b);
            lua_rawseti(s, tableStackPosition, tableIndex);
            tableIndex++;
        }
    }
     return 1;
 }

/** LUA get_distance (area)
 * get_distance(handle being1, handle being2)
 * get_distance(int x1, int y1, int x2, int y2)
 **
 * **Return value:** The distance between the two beings or the two points
 * in pixels.
 */
static int get_distance(lua_State *s)
{
    int x1, y1, x2, y2;
    if (lua_gettop(s) == 2)
    {
        Entity *being1 = checkBeing(s, 1);
        Entity *being2 = checkBeing(s, 2);

        x1 = being1->getComponent<ActorComponent>()->getPosition().x;
        y1 = being1->getComponent<ActorComponent>()->getPosition().y;
        x2 = being2->getComponent<ActorComponent>()->getPosition().x;
        y2 = being2->getComponent<ActorComponent>()->getPosition().y;
    }
    else
    {
        x1 = luaL_checkint(s, 1);
        y1 = luaL_checkint(s, 2);
        x2 = luaL_checkint(s, 3);
        y2 = luaL_checkint(s, 4);
    }
    const int dx = x1 - x2;
    const int dy = y1 - y2;
    const float dist = sqrt((dx * dx) + (dy * dy));
    lua_pushinteger(s, dist);

    return 1;
}


/** LUA_CATEGORY Ability info class (abilityinfo)
 * See the [[abilitys.xml#A script example|abilitys Documentation]] for a
 * script example
 */

/** LUA get_ability_info (abilityinfo)
 * get_ability_info(int abilityId)
 * get_ability_info(string abilityName)
 **
 * **Return value:** This function returns a object of the abilityinfo class.
 * See below for usage of that object.
 *
 * **Note:** When passing the ''abilityName'' as parameter make sure that it is
 * formatted in this way: <setname>_<abilityname> (for eg. "Magic_Healingspell").
 */
static int get_ability_info(lua_State *s)
{
    auto *abilityInfo = checkAbility(s, 1);
    LuaAbilityInfo::push(s, abilityInfo);
    return 1;
}

/** LUA abilityinfo:name (abilityinfo)
 * abilityinfo:name()
 **
 * ** Return value:** The name of the abilityinfo object.
 *
 * **Note:** See [[scripting#get_ability_info|get_ability_info]] for getting a
 * abilityinfo object.
 */
static int abilityinfo_get_name(lua_State *s)
{
    auto *info = LuaAbilityInfo::check(s, 1);
    push(s, info->name);
    return 1;
}

/** LUA abilityinfo:needed_mana (abilityinfo)
 * abilityinfo:needed_mana()
 **
 * ** Return value:** The mana that is needed to use the ability
 *
 * **Note:** See [[scripting#get_ability_info|get_ability_info]] for getting a
 * abilityinfo object.
 */
static int abilityinfo_get_needed_mana(lua_State *s)
{
    auto *info = LuaAbilityInfo::check(s, 1);
    lua_pushinteger(s, info->neededPoints);
    return 1;
}

/** LUA abilityinfo:rechargeable (abilityinfo)
 * abilityinfo:rechargeable()
 **
 * ** Return value:** A boolean value that indicates whether the ability is
 * rechargeable or usuable without recharge.
 *
 * **Note:** See [[scripting#get_ability_info|get_ability_info]] for getting
 * a abilityinfo object.
 */
static int abilityinfo_is_rechargeable(lua_State *s)
{
    auto *info = LuaAbilityInfo::check(s, 1);
    lua_pushboolean(s, info->rechargeable);
    return 1;
}

/** LUA abilityinfo:on_use (abilityinfo)
 * abilityinfo:on_use(function callback)
 **
 * Assigns the ''callback'' as callback for the use event. This function will
 * be called everytime a character uses a ability.
 *
 * **Note:** See [[scripting#get_ability_info|get_ability_info]] for getting
 * a abilityinfo object.
 */
static int abilityinfo_on_use(lua_State *s)
{
    auto *info = LuaAbilityInfo::check(s, 1);
    Script *script = getScript(s);
    luaL_checktype(s, 2, LUA_TFUNCTION);
    script->assignCallback(info->useCallback);
    return 0;
}

/** LUA abilityinfo:on_recharged (abilityinfo)
 * abilityinfo:on_recharged(function callback)
 **
 * Assigns the ''callback'' as callback for the recharged event. This function
 * will be called everytime when the ability is fully recharged.
 *
 * **Note:** See [[scripting#get_ability_info|get_ability_info]] for getting
 * a abilityinfo object.
 */
static int abilityinfo_on_recharged(lua_State *s)
{
    auto *info = LuaAbilityInfo::check(s, 1);
    Script *script = getScript(s);
    luaL_checktype(s, 2, LUA_TFUNCTION);
    script->assignCallback(info->rechargedCallback);
    return 0;
}

/** LUA abilityinfo:category (abilityinfo)
 * abilityinfo:category(function callback)
 **
 * **Return value:** The set-name of the ability as defined in the
 * [[abilities.xml]]
 *
 * **Note:** See [[scripting#get_ability_info|get_ability_info]] for getting
 * a abilityinfo object.
 */
static int abilitiyinfo_get_category(lua_State *s)
{
    auto *info = LuaAbilityInfo::check(s, 1);
    push(s, info->categoryName);
    return 1;
}


/** LUA_CATEGORY Status effect class (statuseffectclass)
 */

/** LUA get_status_effect (statuseffectclass)
 * get_status_effect(string name)
 **
 * **Return value:** This function returns a object of the statuseffect class.
 * See below for usage of that object.
 */
static int get_status_effect(lua_State *s)
{
    const char *name = luaL_checkstring(s, 1);
    LuaStatusEffect::push(s, StatusManager::getStatusByName(name));
    return 1;
}

/** LUA statuseffect:on_tick (statuseffectclass)
 * statuseffect:on_tick(function callback)
 **
 * Sets the callback that gets called for every tick when the status effect
 * is active.
 *
 * **Note:** See [[scripting#get_status_effect|get_status_effect]] for getting
 * a statuseffect object.
 */
static int status_effect_on_tick(lua_State *s)
{
    StatusEffect *statusEffect = LuaStatusEffect::check(s, 1);
    luaL_checktype(s, 2, LUA_TFUNCTION);
    statusEffect->setTickCallback(getScript(s));
    return 0;
}

/** LUA_CATEGORY Monster class (monsterclass)
 */

/** LUA get_monster_class (monsterclass)
 * get_monster_class(int monsterid)
 * get_monster_class(string monstername)
 **
 * **Return value:** This function returns a object of the monster class.
 * See below for usage of that object.
 */
static int get_monster_class(lua_State *s)
{
    LuaMonsterClass::push(s, checkMonsterClass(s, 1));
    return 1;
}

/** LUA get_monster_classes (monsterclass)
 * get_monster_classes()
 **
 * **Return value:** A Table with all monster classes. The id of the monster
 * is the key. The monster class itself the value. See below for the usage of
 * this object.
 */
static int get_monster_classes(lua_State *s)
{
    pushSTLContainer(s, monsterManager->getMonsterClasses());
    return 1;
}

/** LUA monsterclass:on_update (monsterclass)
 * monsterclass:on_update(function callback)
 **
 * Assigns the ''callback'' as callback for the monster update event. This
 * callback will be called every tick for each monster of that class.
 *
 * **Note:** See [[scripting#get_monster_class|get_monster_class]] for getting
 * a monsterclass object.
 */
static int monster_class_on_update(lua_State *s)
{
    MonsterClass *monsterClass = LuaMonsterClass::check(s, 1);
    luaL_checktype(s, 2, LUA_TFUNCTION);
    monsterClass->setUpdateCallback(getScript(s));
    return 0;
}

/** LUA monsterclass:name (monsterclass)
 * monsterclass:name()
 **
 * **Return value:** The name of the monster class.
 */
static int monster_class_get_name(lua_State *s)
{
    MonsterClass *monsterClass = LuaMonsterClass::check(s, 1);
    push(s, monsterClass->getName());
    return 1;
}


/** LUA_CATEGORY Map object class (mapobjectclass)
 */

/** LUA map_get_objects (mapobjectclass)
 * map_get_objects()
 * map_get_objects(string type)
 **
 * **Return value:** A table of all objects or a table of all objects of the
 * given ''type''. See below for usage of these objects.
 */
static int map_get_objects(lua_State *s)
{
    const bool filtered = (lua_gettop(s) == 1);
    const char *filter;
    if (filtered)
    {
        filter = luaL_checkstring(s, 1);
    }

    MapComposite *m = checkCurrentMap(s);
    const std::vector<MapObject*> &objects = m->getMap()->getObjects();

    if (!filtered)
        pushSTLContainer<MapObject*>(s, objects);
    else
    {
        std::vector<MapObject*> filteredObjects;
        for (std::vector<MapObject*>::const_iterator it = objects.begin();
             it != objects.end(); ++it)
        {
            if (utils::compareStrI((*it)->getType(), filter) == 0)
            {
                filteredObjects.push_back(*it);
            }
        }
        pushSTLContainer<MapObject*>(s, filteredObjects);
    }
    return 1;
}

/** LUA mapobject:property (mapobjectclass)
 * mapobject:property(string key)
 **
 * **Return value:** The value of the property of the key ''key'' or nil if
 * the property does not exists.
 *
 * **Note:** See [[scripting#map_get_objects|map_get_objects]] for getting a
 * monsterclass object.
 */
static int map_object_get_property(lua_State *s)
{
    const char *key = luaL_checkstring(s, 2);
    MapObject *obj = LuaMapObject::check(s, 1);

    std::string property = obj->getProperty(key);
    if (!property.empty())
    {
        push(s, property);
        return 1;
    }
    else
    {
        // scripts can check for nil
        return 0;
    }
}

/** LUA mapobject:bounds (mapobjectclass)
 * mapobject:bounds()
 **
 * **Return value:** x, y position and height, width of the ''mapobject''.
 *
 * **Example use:**
 * <code lua>local x, y, width, height = my_mapobject:bounds()</code>
 *
 * **Note:** See [[scripting#map_get_objects|map_get_objects]] for getting a
 * mapobject object.
 */
static int map_object_get_bounds(lua_State *s)
{
    MapObject *obj = LuaMapObject::check(s, 1);
    const Rectangle &bounds = obj->getBounds();
    lua_pushinteger(s, bounds.x);
    lua_pushinteger(s, bounds.y);
    lua_pushinteger(s, bounds.w);
    lua_pushinteger(s, bounds.h);
    return 4;
}

/** LUA mapobject:name (mapobjectclass)
 * mapobject:name()
 **
 * **Return value:** Name as set in the mapeditor of the ''mapobject''.
 *
 * **Note:** See [[scripting#map_get_objects|map_get_objects]] for getting
 * a mapobject object.
 */
static int map_object_get_name(lua_State *s)
{
    MapObject *obj = LuaMapObject::check(s, 1);
    push(s, obj->getName());
    return 1;
}

/** LUA mapobject:type (mapobjectclass)
 * mapobject:type()
 **
 * **Return value:** Type as set in the mapeditor of the ''mapobject''.
 *
 * **Note:** See [[scripting#map_get_objects|map_get_objects]] for getting
 * a mapobject object.
 */
static int map_object_get_type(lua_State *s)
{
    MapObject *obj = LuaMapObject::check(s, 1);
    push(s, obj->getType());
    return 1;
}


/** LUA_CATEGORY Item class (itemclass)
 */

/** LUA get_item_class (itemclass)
 * get_item_class(int itemid)
 * get_item_class(string itemname)
 **
 * **Return value:** This function returns a object of the item class.
 * See below for usage of that object.
 */
static int get_item_class(lua_State *s)
{
    LuaItemClass::push(s, checkItemClass(s, 1));
    return 1;
}

/** LUA itemclass:on (itemclass)
 * itemclass:on(string event, function callback)
 **
 * Assigns ''callback'' as callback for the ''event'' event.
 *
 * **Note:** See [[scripting#get_item_class|get_item_class]] for getting
 * a itemclass object.
 */
static int item_class_on(lua_State *s)
{
    ItemClass *itemClass = LuaItemClass::check(s, 1);
    const char *event = luaL_checkstring(s, 2);
    luaL_checktype(s, 3, LUA_TFUNCTION);
    itemClass->setEventCallback(event, getScript(s));
    return 0;
}

/** LUA itemclass:name (itemclass)
 * itemclass:name()
 **
 * **Return value:** The name of the item class.
 */
static int item_class_get_name(lua_State *s)
{
    ItemClass *itemClass = LuaItemClass::check(s, 1);
    push(s, itemClass->getName());
    return 1;
}

/**
 * Returns four useless tables for testing the STL container push wrappers.
 * This function can be removed when there are more useful functions which use
 * them.
 */
static int test_tableget(lua_State *s)
{
    std::list<float> list;
    std::vector<std::string> svector;
    std::vector<int> ivector;
    std::map<std::string, std::string> map;
    std::set<int> set;

    LOG_INFO("Pushing Float List");
    list.push_back(12.636);
    list.push_back(0.0000000045656);
    list.push_back(185645445634566.346);
    list.push_back(7835458.11);
    pushSTLContainer<float>(s, list);

    LOG_INFO("Pushing String Vector");
    svector.push_back("All");
    svector.push_back("your");
    svector.push_back("base");
    svector.push_back("are");
    svector.push_back("belong");
    svector.push_back("to");
    svector.push_back("us!");
    pushSTLContainer<std::string>(s, svector);

    LOG_INFO("Pushing Integer Vector");
    ivector.resize(10);
    for (int i = 1; i < 10; i++)
        ivector[i - 1] = i * i;

    pushSTLContainer<int>(s, ivector);

    LOG_INFO("Pushing String/String Map");
    map["Apple"] = "red";
    map["Banana"] = "yellow";
    map["Lime"] = "green";
    map["Plum"] = "blue";
    pushSTLContainer<std::string, std::string>(s, map);

    LOG_INFO("Pushing Integer Set");
    set.insert(12);
    set.insert(8);
    set.insert(14);
    set.insert(10);
    pushSTLContainer<int>(s, set);

    return 5;
}



static int require_loader(lua_State *s)
{
    // Add .lua extension (maybe only do this when it doesn't have it already)
    const char *file = luaL_checkstring(s, 1);
    std::string filename = file;
    filename.append(".lua");

    const std::string path = ResourceManager::resolve(filename);
    if (!path.empty())
        luaL_loadfile(s, path.c_str());
    else
        lua_pushliteral(s, "File not found");

    return 1;
}


LuaScript::LuaScript():
    nbArgs(-1)
{
    mRootState = luaL_newstate();
    mCurrentState = mRootState;
    luaL_openlibs(mRootState);

    // Register package loader that goes through the resource manager
    // package.loaders[2] = require_loader
    lua_getglobal(mRootState, "package");
#if LUA_VERSION_NUM < 502
    lua_getfield(mRootState, -1, "loaders");
#else
    lua_getfield(mRootState, -1, "searchers");
#endif
    lua_pushcfunction(mRootState, require_loader);
    lua_rawseti(mRootState, -2, 2);
    lua_pop(mRootState, 2);

    // Put the callback functions in the scripting environment.
    static luaL_Reg const callbacks[] = {
        { "on_update_derived_attribute",    on_update_derived_attribute       },
        { "on_recalculate_base_attribute",  on_recalculate_base_attribute     },
        { "on_character_death",             on_character_death                },
        { "on_character_death_accept",      on_character_death_accept         },
        { "on_character_login",             on_character_login                },
        { "on_being_death",                 on_being_death                    },
        { "on_entity_remove",               on_entity_remove                  },
        { "on_update",                      on_update                         },
        { "on_create_npc_delayed",          on_create_npc_delayed             },
        { "on_map_initialize",              on_map_initialize                 },
        { "on_craft",                       on_craft                          },
        { "on_mapvar_changed",              on_mapvar_changed                 },
        { "on_worldvar_changed",            on_worldvar_changed               },
        { "on_mapupdate",                   on_mapupdate                      },
        { "get_item_class",                 get_item_class                    },
        { "get_monster_class",              get_monster_class                 },
        { "get_monster_classes",            get_monster_classes               },
        { "get_status_effect",              get_status_effect                 },
        { "npc_create",                     npc_create                        },
        { "say",                            say                               },
        { "ask",                            ask                               },
        { "ask_number",                     ask_number                        },
        { "ask_string",                     ask_string                        },
        { "trade",                          trade                             },
        { "npc_post",                       npc_post                          },
        { "npc_enable",                     npc_enable                        },
        { "npc_disable",                    npc_disable                       },
        { "chr_get_quest",                  chr_get_quest                     },
        { "chr_set_quest",                  chr_set_quest                     },
        { "chr_request_quest",              chr_request_quest                 },
        { "chr_try_get_quest",              chr_try_get_quest                 },
        { "getvar_map",                     getvar_map                        },
        { "setvar_map",                     setvar_map                        },
        { "getvar_world",                   getvar_world                      },
        { "setvar_world",                   setvar_world                      },
        { "chr_get_post",                   chr_get_post                      },
        { "xp_for_level",                   xp_for_level                      },
        { "monster_create",                 monster_create                    },
        { "trigger_create",                 trigger_create                    },
        { "get_beings_in_circle",           get_beings_in_circle              },
        { "get_beings_in_rectangle",        get_beings_in_rectangle           },
        { "get_character_by_name",          get_character_by_name             },
        { "effect_create",                  effect_create                     },
        { "test_tableget",                  test_tableget                     },
        { "get_map_id",                     get_map_id                        },
        { "get_map_property",               get_map_property                  },
        { "is_walkable",                    is_walkable                       },
        { "get_path_length",                get_path_length                   },
        { "map_get_pvp",                    map_get_pvp                       },
        { "item_drop",                      item_drop                         },
        { "log",                            log                               },
        { "get_distance",                   get_distance                      },
        { "map_get_objects",                map_get_objects                   },
        { "announce",                       announce                          },
        { "get_ability_info",               get_ability_info                  },
        { nullptr, nullptr }
    };
#if LUA_VERSION_NUM < 502
    lua_pushvalue(mRootState, LUA_GLOBALSINDEX);
    luaL_register(mRootState, nullptr, callbacks);
#else
    lua_pushglobaltable(mRootState);
    luaL_setfuncs(mRootState, callbacks, 0);
#endif
    lua_pop(mRootState, 1);                     // pop the globals table

    static luaL_Reg const members_Entity[] = {
        { "remove",                         entity_remove                     },
        { "say",                            entity_say                        },
        { "message",                        entity_message                    },
        { "inventory",                      entity_get_inventory              },
        { "inv_change",                     entity_inv_change                 },
        { "inv_count",                      entity_inv_count                  },
        { "equipment",                      entity_get_equipment              },
        { "equip_slot",                     entity_equip_slot                 },
        { "equip_item",                     entity_equip_item                 },
        { "unequip_slot",                   entity_unequip_slot               },
        { "unequip_item",                   entity_unequip_item               },
        { "set_ability_mana",               entity_set_ability_mana           },
        { "ability_mana",                   entity_get_ability_mana           },
        { "cooldown_ability",               entity_cooldown_ability           },
        { "walk",                           entity_walk                       },
        { "destination",                    entity_destination                },
        { "heal",                           entity_heal                       },
        { "name",                           entity_get_name                   },
        { "type",                           entity_get_type                   },
        { "action",                         entity_get_action                 },
        { "set_action",                     entity_set_action                 },
        { "direction",                      entity_get_direction              },
        { "set_direction",                  entity_set_direction              },
        { "set_walkmask",                   entity_set_walkmask               },
        { "walkmask",                       entity_get_walkmask               },
        { "warp",                           entity_warp                       },
        { "position",                       entity_get_position               },
        { "x",                              entity_get_x                      },
        { "y",                              entity_get_y                      },
        { "base_attribute",                 entity_get_base_attribute         },
        { "set_base_attribute",             entity_set_base_attribute         },
        { "modified_attribute",             entity_get_modified_attribute     },
        { "apply_attribute_modifier",       entity_apply_attribute_modifier   },
        { "remove_attribute_modifier",      entity_remove_attribute_modifier  },
        { "gender",                         entity_get_gender                 },
        { "set_gender",                     entity_set_gender                 },
        { "level",                          entity_get_level                  },
        { "xp",                             entity_get_xp                     },
        { "give_xp",                        entity_give_xp                    },
        { "hair_color",                     entity_get_hair_color             },
        { "set_hair_color",                 entity_set_hair_color             },
        { "hair_style",                     entity_get_hair_style             },
        { "set_hair_style",                 entity_set_hair_style             },
        { "kill_count",                     entity_get_kill_count             },
        { "rights",                         entity_get_rights                 },
        { "kick",                           entity_kick                       },
        { "mapid",                          entity_get_mapid                  },
        { "register",                       entity_register                   },
        { "shake_screen",                   entity_shake_screen               },
        { "show_text_particle",             entity_show_text_particle         },
        { "give_ability",                   entity_give_ability               },
        { "has_ability",                    entity_has_ability                },
        { "take_ability",                   entity_take_ability               },
        { "use_ability",                    entity_use_ability                },
        { "monster_id",                     entity_get_monster_id             },
        { "apply_status",                   entity_apply_status               },
        { "remove_status",                  entity_remove_status              },
        { "has_status",                     entity_has_status                 },
        { "status_time",                    entity_get_status_time            },
        { "set_status_time",                entity_set_status_time            },
        { "add_hit_taken",                  entity_add_hit_taken              },
        { nullptr, nullptr }
    };

    static luaL_Reg const members_ItemClass[] = {
        { "on",                             item_class_on                     },
        { "name",                           item_class_get_name               },
        { nullptr, nullptr }
    };

    static luaL_Reg const members_MapObject[] = {
        { "property",                       map_object_get_property           },
        { "bounds",                         map_object_get_bounds             },
        { "name",                           map_object_get_name               },
        { "type",                           map_object_get_type               },
        { nullptr, nullptr }
    };

    static luaL_Reg const members_MonsterClass[] = {
        { "on_update",                      monster_class_on_update           },
        { "name",                           monster_class_get_name            },
        { nullptr, nullptr }
    };

    static luaL_Reg const members_StatusEffect[] = {
        { "on_tick",                        status_effect_on_tick             },
        { nullptr, nullptr }
    };

    static luaL_Reg const members_AbilityInfo[] = {
        { "name",                           abilityinfo_get_name              },
        { "needed_mana",                    abilityinfo_get_needed_mana       },
        { "rechargeable",                   abilityinfo_is_rechargeable       },
        { "on_use",                         abilityinfo_on_use                },
        { "on_recharged",                   abilityinfo_on_recharged          },
        { "category",                       abilitiyinfo_get_category         },
        { nullptr, nullptr}
    };

    LuaEntity::registerType(mRootState, "Entity", members_Entity);
    LuaItemClass::registerType(mRootState, "ItemClass", members_ItemClass);
    LuaMapObject::registerType(mRootState, "MapObject", members_MapObject);
    LuaMonsterClass::registerType(mRootState, "MonsterClass", members_MonsterClass);
    LuaStatusEffect::registerType(mRootState, "StatusEffect", members_StatusEffect);
    LuaAbilityInfo::registerType(mRootState, "AbilityInfo", members_AbilityInfo);

    // Make script object available to callback functions.
    lua_pushlightuserdata(mRootState, const_cast<char *>(&registryKey));
    lua_pushlightuserdata(mRootState, this);
    lua_rawset(mRootState, LUA_REGISTRYINDEX);

    // Push the error handler to first index of the stack
    lua_getglobal(mRootState, "debug");
    lua_getfield(mRootState, -1, "traceback");
    lua_remove(mRootState, 1);                  // remove the 'debug' table

    loadFile("scripts/lua/libmana.lua");
}