summaryrefslogtreecommitdiffstats
path: root/src/Bindings/LuaState.cpp
blob: 0541af7935180436ef3fb022900176d3bd5720a9 (plain) (blame)
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

// LuaState.cpp

// Implements the cLuaState class representing the wrapper over lua_State *, provides associated helper functions

#include "Globals.h"
#include "LuaState.h"

extern "C"
{
	#include "lua/src/lualib.h"
}

#undef TOLUA_TEMPLATE_BIND
#include "tolua++/include/tolua++.h"
#include "Bindings.h"
#include "ManualBindings.h"
#include "DeprecatedBindings.h"
#include "LuaJson.h"
#include "../Entities/Entity.h"
#include "../BlockEntities/BlockEntity.h"
#include "../DeadlockDetect.h"
#include "../UUID.h"





// Hotpatching the Macro to prevent a Clang Warning (0 for pointer used)
#undef  lua_tostring
#define lua_tostring(L, i) lua_tolstring(L, (i), nullptr)





// fwd: "SQLite/lsqlite3.c"
extern "C"
{
	int luaopen_lsqlite3(lua_State * L);
}

// fwd: "LuaExpat/lxplib.c":
extern "C"
{
	int luaopen_lxp(lua_State * L);
}





const cLuaState::cRet cLuaState::Return = {};
const cLuaState::cNil cLuaState::Nil = {};





////////////////////////////////////////////////////////////////////////////////
// cCanonLuaStates:

/** Tracks the canon cLuaState instances for each lua_State pointer.
Used for tracked refs - the ref needs to be tracked by a single cLuaState (the canon state), despite being created from a different (attached) cLuaState.
The canon state must be available without accessing the Lua state itself (so it cannot be stored within Lua). */
class cCanonLuaStates
{
public:
	/** Returns the canon Lua state for the specified lua_State pointer. */
	static cLuaState * GetCanonState(lua_State * a_LuaState)
	{
		auto & inst = GetInstance();
		cCSLock lock(inst.m_CS);
		auto itr = inst.m_CanonStates.find(a_LuaState);
		if (itr == inst.m_CanonStates.end())
		{
			return nullptr;
		}
		return itr->second;
	}

	/** Adds a new canon cLuaState instance to the map.
	Used when a new Lua state is created, this informs the map that a new canon Lua state should be tracked. */
	static void Add(cLuaState & a_LuaState)
	{
		auto & inst = GetInstance();
		cCSLock lock(inst.m_CS);
		ASSERT(inst.m_CanonStates.find(a_LuaState) == inst.m_CanonStates.end());
		inst.m_CanonStates[a_LuaState.operator lua_State *()] = &a_LuaState;
	}

	/** Removes the bindings between the specified canon state and its lua_State pointer.
	Used when a Lua state is being closed. */
	static void Remove(cLuaState & a_LuaState)
	{
		auto & inst = GetInstance();
		cCSLock lock(inst.m_CS);
		auto itr = inst.m_CanonStates.find(a_LuaState);
		ASSERT(itr != inst.m_CanonStates.end());
		inst.m_CanonStates.erase(itr);
	}

protected:
	/** The mutex protecting m_CanonStates against multithreaded access. */
	cCriticalSection m_CS;

	/** Map of lua_State pointers to their canon cLuaState instances. */
	std::map<lua_State *, cLuaState *> m_CanonStates;


	/** Returns the singleton instance of this class. */
	static cCanonLuaStates & GetInstance(void)
	{
		static cCanonLuaStates canonLuaStates;
		return canonLuaStates;
	}
};





////////////////////////////////////////////////////////////////////////////////
// cLuaStateTracker:

void cLuaStateTracker::Add(cLuaState & a_LuaState)
{
	auto & Instance = Get();
	cCSLock Lock(Instance.m_CSLuaStates);
	Instance.m_LuaStates.push_back(&a_LuaState);
}





void cLuaStateTracker::Del(cLuaState & a_LuaState)
{
	auto & Instance = Get();
	cCSLock Lock(Instance.m_CSLuaStates);
	Instance.m_LuaStates.erase(
		std::remove_if(
			Instance.m_LuaStates.begin(), Instance.m_LuaStates.end(),
			[&a_LuaState](cLuaStatePtr a_StoredLuaState)
			{
				return (&a_LuaState == a_StoredLuaState);
			}
		),
		Instance.m_LuaStates.end()
	);
}





AString cLuaStateTracker::GetStats(void)
{
	auto & Instance = Get();
	cCSLock Lock(Instance.m_CSLuaStates);
	AString res;
	int Total = 0;
	for (auto state: Instance.m_LuaStates)
	{
		int Mem = 0;
		if (!state->Call("collectgarbage", "count", cLuaState::Return, Mem))
		{
			res.append(Printf("Cannot query memory for state \"%s\"\n", state->GetSubsystemName().c_str()));
		}
		else
		{
			res.append(Printf("State \"%s\" is using %d KiB of memory\n", state->GetSubsystemName().c_str(), Mem));
			Total += Mem;
		}
	}
	res.append(Printf("Total memory used by Lua: %d KiB\n", Total));
	return res;
}





cLuaStateTracker & cLuaStateTracker::Get(void)
{
	static cLuaStateTracker Inst;  // The singleton
	return Inst;
}





////////////////////////////////////////////////////////////////////////////////
// cLuaState::cTrackedRef:

cLuaState::cTrackedRef::cTrackedRef(void):
	m_CS(nullptr)
{
}





bool cLuaState::cTrackedRef::RefStack(cLuaState & a_LuaState, int a_StackPos)
{
	// Clear any previous callback:
	Clear();

	// Add self to LuaState's callback-tracking:
	auto canonState = a_LuaState.QueryCanonLuaState();
	canonState->TrackRef(*this);

	// Store the new callback:
	m_CS = &(canonState->m_CS);
	m_Ref.RefStack(*canonState, a_StackPos);
	return true;
}





void cLuaState::cTrackedRef::Clear(void)
{
	// Free the reference:
	lua_State * luaState = nullptr;
	{
		auto cs = m_CS.load();
		if (cs != nullptr)
		{
			cCSLock Lock(*cs);
			if (!m_Ref.IsValid())
			{
				return;
			}
			luaState = m_Ref.GetLuaState();
			m_Ref.UnRef();
		}
	}
	m_CS = nullptr;

	// Remove from LuaState's callback-tracking:
	if (luaState == nullptr)
	{
		return;
	}
	cLuaState(luaState).UntrackRef(*this);
}





bool cLuaState::cTrackedRef::IsValid(void)
{
	auto cs = m_CS.load();
	if (cs == nullptr)
	{
		return false;
	}
	cCSLock lock(*cs);
	return m_Ref.IsValid();
}





bool cLuaState::cTrackedRef::IsSameLuaState(cLuaState & a_LuaState)
{
	auto cs = m_CS.load();
	if (cs == nullptr)
	{
		return false;
	}
	cCSLock lock(*cs);
	if (!m_Ref.IsValid())
	{
		return false;
	}
	auto canonState = a_LuaState.QueryCanonLuaState();
	if (canonState == nullptr)
	{
		return false;
	}
	return (m_Ref.GetLuaState() == static_cast<lua_State *>(*canonState));
}





void cLuaState::cTrackedRef::Invalidate(void)
{
	auto cs = m_CS.load();
	if (cs == nullptr)
	{
		// Already invalid
		return;
	}
	cCSLock Lock(*cs);
	if (!m_Ref.IsValid())
	{
		LOGD("%s: Inconsistent callback at %p, has a CS but an invalid Ref. This should not happen",
			__FUNCTION__, static_cast<void *>(this)
		);
		return;
	}
	m_Ref.UnRef();
	m_CS = nullptr;
}





////////////////////////////////////////////////////////////////////////////////
// cLuaState::cCallback:

bool cLuaState::cCallback::RefStack(cLuaState & a_LuaState, int a_StackPos)
{
	// Check if the stack contains a function:
	if (!lua_isfunction(a_LuaState, a_StackPos))
	{
		return false;
	}

	return Super::RefStack(a_LuaState, a_StackPos);
}





////////////////////////////////////////////////////////////////////////////////
// cLuaState::cOptionalCallback:

bool cLuaState::cOptionalCallback::RefStack(cLuaState & a_LuaState, int a_StackPos)
{
	// If the stack pos is nil, make this an empty callback:
	if (lua_isnil(a_LuaState, a_StackPos))
	{
		Clear();
		return true;
	}

	// Use default cCallback implementation:
	return Super::RefStack(a_LuaState, a_StackPos);
}





////////////////////////////////////////////////////////////////////////////////
// cLuaState::cTableRef:

bool cLuaState::cTableRef::RefStack(cLuaState & a_LuaState, int a_StackPos)
{
	// Check if the stack contains a table:
	if (!lua_istable(a_LuaState, a_StackPos))
	{
		return false;
	}

	return Super::RefStack(a_LuaState, a_StackPos);
}





////////////////////////////////////////////////////////////////////////////////
// cLuaState::cStackTable:

cLuaState::cStackTable::cStackTable(cLuaState & a_LuaState, int a_StackPos):
	m_LuaState(a_LuaState),
	m_StackPos(a_StackPos)
{
	ASSERT(lua_istable(a_LuaState, a_StackPos));
}





void cLuaState::cStackTable::ForEachArrayElement(cFunctionRef<bool(cLuaState & a_LuaState, int a_Index)> a_ElementCallback) const
{
	auto numElements = luaL_getn(m_LuaState, m_StackPos);
	#ifdef _DEBUG
		auto stackTop = lua_gettop(m_LuaState);
	#endif
	for (int idx = 1; idx <= numElements; idx++)
	{
		// Push the idx-th element of the array onto stack top and call the callback:
		lua_rawgeti(m_LuaState, m_StackPos, idx);
		auto shouldAbort = a_ElementCallback(m_LuaState, idx);
		ASSERT(lua_gettop(m_LuaState) == stackTop + 1);  // The element callback must not change the Lua stack below the value
		lua_pop(m_LuaState, 1);
		if (shouldAbort)
		{
			// The callback wants to abort
			return;
		}
	}
}





void cLuaState::cStackTable::ForEachElement(cFunctionRef<bool(cLuaState & a_LuaState)> a_ElementCallback) const
{
	#ifdef _DEBUG
		auto stackTop = lua_gettop(m_LuaState);
	#endif
	lua_pushvalue(m_LuaState, m_StackPos);  // Stk: <table>
	lua_pushnil(m_LuaState);                // Stk: <table> nil
	while (lua_next(m_LuaState, -2))        // Stk: <table> <key> <val>
	{
		auto shouldAbort = a_ElementCallback(m_LuaState);
		ASSERT(lua_gettop(m_LuaState) == stackTop + 3);  // The element callback must not change the Lua stack below the value
		lua_pop(m_LuaState, 1);  // Stk: <table> <key>
		if (shouldAbort)
		{
			// The callback wants to abort
			lua_pop(m_LuaState, 2);  // Stk: empty
			return;
		}
	}
	// Stk: <table>
	lua_pop(m_LuaState, 1);  // Stk: empty
}





////////////////////////////////////////////////////////////////////////////////
// cLuaState:

cLuaState::cLuaState(const AString & a_SubsystemName) :
	m_LuaState(nullptr),
	m_IsOwned(false),
	m_SubsystemName(a_SubsystemName),
	m_NumCurrentFunctionArgs(-1)
{
}





cLuaState::cLuaState(lua_State * a_AttachState) :
	m_LuaState(a_AttachState),
	m_IsOwned(false),
	m_SubsystemName("<attached>"),
	m_NumCurrentFunctionArgs(-1)
{
}





cLuaState::~cLuaState()
{
	if (IsValid())
	{
		if (m_IsOwned)
		{
			Close();
		}
		else
		{
			Detach();
		}
	}
}





void cLuaState::Create(void)
{
	if (m_LuaState != nullptr)
	{
		LOGWARNING("%s: Trying to create an already-existing LuaState, ignoring.", __FUNCTION__);
		return;
	}
	m_LuaState = lua_open();
	luaL_openlibs(m_LuaState);
	m_IsOwned = true;
	cLuaStateTracker::Add(*this);
	cCanonLuaStates::Add(*this);
}





void cLuaState::RegisterAPILibs(void)
{
	auto top = lua_gettop(m_LuaState);
	tolua_AllToLua_open(m_LuaState);
	ASSERT(top == lua_gettop(m_LuaState));
	cManualBindings::Bind(m_LuaState);
	ASSERT(top == lua_gettop(m_LuaState));
	DeprecatedBindings::Bind(m_LuaState);
	ASSERT(top == lua_gettop(m_LuaState));
	cLuaJson::Bind(*this);
	ASSERT(top == lua_gettop(m_LuaState));
	luaopen_lsqlite3(m_LuaState);
	if (top == lua_gettop(m_LuaState) - 1)
	{
		// lsqlite3 left the "sqlite3" table on the stack, pop it:
		lua_pop(m_LuaState, 1);
	}
	ASSERT(top == lua_gettop(m_LuaState));
	luaopen_lxp(m_LuaState);
	if (top == lua_gettop(m_LuaState) - 1)
	{
		// lxp left the unregistered "lxp" table on the stack, register and pop it (#3304):
		lua_setglobal(m_LuaState, "lxp");
	}
	ASSERT(top == lua_gettop(m_LuaState));
}





void cLuaState::Close(void)
{
	if (m_LuaState == nullptr)
	{
		LOGWARNING("%s: Trying to close an invalid LuaState, ignoring.", __FUNCTION__);
		return;
	}
	if (!m_IsOwned)
	{
		LOGWARNING(
			"%s: Detected mis-use, calling Close() on an attached state (0x%p). Detaching instead.",
			__FUNCTION__, static_cast<void *>(m_LuaState)
		);
		Detach();
		return;
	}

	// Invalidate all tracked refs:
	{
		cCSLock Lock(m_CSTrackedRefs);
		for (auto & r: m_TrackedRefs)
		{
			r->Invalidate();
		}
		m_TrackedRefs.clear();
	}

	cCanonLuaStates::Remove(*this);
	cLuaStateTracker::Del(*this);
	lua_close(m_LuaState);
	m_LuaState = nullptr;
	m_IsOwned = false;
}





void cLuaState::Attach(lua_State * a_State)
{
	if (m_LuaState != nullptr)
	{
		LOGINFO("%s: Already contains a LuaState (0x%p), will be closed / detached.", __FUNCTION__, static_cast<void *>(m_LuaState));
		if (m_IsOwned)
		{
			Close();
		}
		else
		{
			Detach();
		}
	}
	m_LuaState = a_State;
	m_IsOwned = false;
}





void cLuaState::Detach(void)
{
	if (m_LuaState == nullptr)
	{
		return;
	}
	if (m_IsOwned)
	{
		LOGWARNING(
			"%s: Detected a mis-use, calling Detach() when the state is owned. Closing the owned state (0x%p).",
			__FUNCTION__, static_cast<void *>(m_LuaState)
		);
		Close();
		return;
	}
	m_LuaState = nullptr;
}





void cLuaState::AddPackagePath(const AString & a_PathVariable, const AString & a_Path)
{
	ASSERT_LUA_STACK_BALANCE(m_LuaState);

	// Get the current path:
	lua_getfield(m_LuaState, LUA_GLOBALSINDEX, "package");                           // Stk: <package>
	lua_getfield(m_LuaState, -1, a_PathVariable.c_str());                            // Stk: <package> <package.path>
	size_t len = 0;
	const char * PackagePath = lua_tolstring(m_LuaState, -1, &len);

	// Append the new path:
	AString NewPackagePath(PackagePath, len);
	NewPackagePath.append(LUA_PATHSEP);
	NewPackagePath.append(a_Path);

	// Set the new path to the environment:
	lua_pop(m_LuaState, 1);                                                          // Stk: <package>
	lua_pushlstring(m_LuaState, NewPackagePath.c_str(), NewPackagePath.length());    // Stk: <package> <NewPackagePath>
	lua_setfield(m_LuaState, -2, a_PathVariable.c_str());                            // Stk: <package>
	lua_pop(m_LuaState, 1);                                                          // Stk: -
}





bool cLuaState::LoadFile(const AString & a_FileName, bool a_LogWarnings)
{
	ASSERT(IsValid());
	ASSERT_LUA_STACK_BALANCE(m_LuaState);

	// Load the file:
	int s = luaL_loadfile(m_LuaState, a_FileName.c_str());
	if (s != 0)
	{
		if (a_LogWarnings)
		{
			LOGWARNING("Can't load %s because of a load error in file %s: %d (%s)", m_SubsystemName.c_str(), a_FileName.c_str(), s, lua_tostring(m_LuaState, -1));
		}
		lua_pop(m_LuaState, 1);
		return false;
	}

	// Execute the globals:
	s = lua_pcall(m_LuaState, 0, 0, 0);
	if (s != 0)
	{
		if (a_LogWarnings)
		{
			LOGWARNING("Can't load %s because of an initialization error in file %s: %d (%s)", m_SubsystemName.c_str(), a_FileName.c_str(), s, lua_tostring(m_LuaState, -1));
		}
		lua_pop(m_LuaState, 1);
		return false;
	}

	return true;
}





bool cLuaState::LoadString(const AString & a_StringToLoad, const AString & a_FileName, bool a_LogWarnings)
{
	ASSERT(IsValid());
	ASSERT_LUA_STACK_BALANCE(m_LuaState);

	// Load the file:
	int s = luaL_loadstring(m_LuaState, a_StringToLoad.c_str());
	if (s != 0)
	{
		if (a_LogWarnings)
		{
			LOGWARNING("Can't load %s because of a load error in string from \"%s\": %d (%s)", m_SubsystemName.c_str(), a_FileName.c_str(), s, lua_tostring(m_LuaState, -1));
		}
		lua_pop(m_LuaState, 1);
		return false;
	}

	// Execute the globals:
	s = lua_pcall(m_LuaState, 0, LUA_MULTRET, 0);
	if (s != 0)
	{
		if (a_LogWarnings)
		{
			LOGWARNING("Can't load %s because of an initialization error in string from \"%s\": %d (%s)", m_SubsystemName.c_str(), a_FileName.c_str(), s, lua_tostring(m_LuaState, -1));
		}
		lua_pop(m_LuaState, 1);
		return false;
	}

	return true;
}





bool cLuaState::HasFunction(const char * a_FunctionName)
{
	if (!IsValid())
	{
		// This happens if cPlugin::Initialize() fails with an error
		return false;
	}

	ASSERT_LUA_STACK_BALANCE(m_LuaState);
	lua_getglobal(m_LuaState, a_FunctionName);
	bool res = (!lua_isnil(m_LuaState, -1) && lua_isfunction(m_LuaState, -1));
	lua_pop(m_LuaState, 1);
	return res;
}





bool cLuaState::PushFunction(const char * a_FunctionName)
{
	ASSERT(m_NumCurrentFunctionArgs == -1);  // If not, there's already something pushed onto the stack

	if (!IsValid())
	{
		// This happens if cPlugin::Initialize() fails with an error
		return false;
	}

	// Push the error handler for lua_pcall()
	lua_pushcfunction(m_LuaState, &ReportFnCallErrors);

	lua_getglobal(m_LuaState, a_FunctionName);
	if (!lua_isfunction(m_LuaState, -1))
	{
		LOGWARNING("Error in %s: Could not find function %s()", m_SubsystemName.c_str(), a_FunctionName);
		lua_pop(m_LuaState, 2);
		return false;
	}
	m_CurrentFunctionName.assign(a_FunctionName);
	m_NumCurrentFunctionArgs = 0;
	return true;
}





bool cLuaState::PushFunction(const cRef & a_FnRef)
{
	ASSERT(IsValid());
	ASSERT(m_NumCurrentFunctionArgs == -1);  // If not, there's already something pushed onto the stack

	// Push the error handler for lua_pcall()
	lua_pushcfunction(m_LuaState, &ReportFnCallErrors);

	lua_rawgeti(m_LuaState, LUA_REGISTRYINDEX, static_cast<int>(a_FnRef));  // same as lua_getref()
	if (!lua_isfunction(m_LuaState, -1))
	{
		lua_pop(m_LuaState, 2);
		return false;
	}
	m_CurrentFunctionName = "<callback>";
	m_NumCurrentFunctionArgs = 0;
	return true;
}





bool cLuaState::PushFunction(const cRef & a_TableRef, const char * a_FnName)
{
	ASSERT(IsValid());
	ASSERT(m_NumCurrentFunctionArgs == -1);  // If not, there's already something pushed onto the stack

	if (!a_TableRef.IsValid())
	{
		return false;
	}

	// Push the error handler for lua_pcall()
	lua_pushcfunction(m_LuaState, &ReportFnCallErrors);

	// Get the function from the table:
	lua_rawgeti(m_LuaState, LUA_REGISTRYINDEX, static_cast<int>(a_TableRef));
	if (!lua_istable(m_LuaState, -1))
	{
		// Not a table, bail out
		lua_pop(m_LuaState, 2);
		return false;
	}
	lua_getfield(m_LuaState, -1, a_FnName);
	if (lua_isnil(m_LuaState, -1) || !lua_isfunction(m_LuaState, -1))
	{
		// Not a valid function, bail out
		lua_pop(m_LuaState, 3);
		return false;
	}

	// Pop the table off the stack:
	lua_remove(m_LuaState, -2);

	Printf(m_CurrentFunctionName, "<table-callback %s>", a_FnName);
	m_NumCurrentFunctionArgs = 0;
	return true;
}





void cLuaState::Push(const AString & a_String)
{
	ASSERT(IsValid());

	lua_pushlstring(m_LuaState, a_String.data(), a_String.size());
}





void cLuaState::Push(const AStringMap & a_Dictionary)
{
	ASSERT(IsValid());

	lua_createtable(m_LuaState, 0, static_cast<int>(a_Dictionary.size()));
	int newTable = lua_gettop(m_LuaState);
	for (const auto & item: a_Dictionary)
	{
		Push(item.first);   // key
		Push(item.second);  // value
		lua_rawset(m_LuaState, newTable);
	}
}





void cLuaState::Push(const AStringVector & a_Vector)
{
	ASSERT(IsValid());

	lua_createtable(m_LuaState, static_cast<int>(a_Vector.size()), 0);
	int newTable = lua_gettop(m_LuaState);
	int index = 1;
	for (AStringVector::const_iterator itr = a_Vector.begin(), end = a_Vector.end(); itr != end; ++itr, ++index)
	{
		tolua_pushstring(m_LuaState, itr->c_str());
		lua_rawseti(m_LuaState, newTable, index);
	}
}





void cLuaState::Push(const char * a_Value)
{
	ASSERT(IsValid());

	tolua_pushstring(m_LuaState, a_Value);
}





void cLuaState::Push(const cItem & a_Item)
{
	ASSERT(IsValid());
	auto c = new cItem(a_Item);
	tolua_pushusertype_and_takeownership(m_LuaState, c, "cItem");
}





void cLuaState::Push(const cNil & a_Nil)
{
	ASSERT(IsValid());

	lua_pushnil(m_LuaState);
}





void cLuaState::Push(const cLuaState::cRef & a_Ref)
{
	ASSERT(IsValid());

	lua_rawgeti(m_LuaState, LUA_REGISTRYINDEX, static_cast<int>(a_Ref));
}





void cLuaState::Push(const Vector3d & a_Vector)
{
	ASSERT(IsValid());
	auto c = new Vector3d(a_Vector);
	tolua_pushusertype_and_takeownership(m_LuaState, c, "Vector3<double>");
}





void cLuaState::Push(const Vector3i & a_Vector)
{
	ASSERT(IsValid());
	auto c = new Vector3i(a_Vector);
	tolua_pushusertype_and_takeownership(m_LuaState, c, "Vector3<int>");
}





void cLuaState::Push(bool a_Value)
{
	ASSERT(IsValid());

	tolua_pushboolean(m_LuaState, a_Value ? 1 : 0);
}





void cLuaState::Push(const cEntity * a_Entity)
{
	// Once we can make Lua understand constness, this function shall receive a corresponding function body
	Push(const_cast<cEntity * >(a_Entity));
}





void cLuaState::Push(cEntity * a_Entity)
{
	ASSERT(IsValid());

	if (a_Entity == nullptr)
	{
		lua_pushnil(m_LuaState);
	}
	else
	{
		const char * ClassName = [&]
			{
				switch (a_Entity->GetEntityType())
				{
					case cEntity::etBoat:         return "cBoat";
					case cEntity::etExpOrb:       return "cExpOrb";
					case cEntity::etFallingBlock: return "cFallingBlock";
					case cEntity::etFloater:      return "cFloater";
					case cEntity::etItemFrame:    return "cItemFrame";
					case cEntity::etLeashKnot:    return "cLeashKnot";
					case cEntity::etPainting:     return "cPainting";
					case cEntity::etPickup:       return "cPickup";
					case cEntity::etPlayer:       return "cPlayer";
					case cEntity::etTNT:          return "cTNTEntity";

					case cEntity::etMonster:
					{
						// Don't push specific mob types, as those are not exported in the API:
						return "cMonster";
					}
					case cEntity::etProjectile:
					{
						// Push the specific projectile type:
						return a_Entity->GetClass();
					}

					case cEntity::etEntity:
					case cEntity::etEnderCrystal:
					case cEntity::etMinecart:
					{
						// Push the generic entity class type:
						return "cEntity";
					}
				}  // switch (EntityType)
				UNREACHABLE("Unsupported entity type");
			}();
		tolua_pushusertype(m_LuaState, a_Entity, ClassName);
	}
}





void cLuaState::Push(cLuaServerHandle * a_ServerHandle)
{
	ASSERT(IsValid());

	tolua_pushusertype(m_LuaState, a_ServerHandle, "cServerHandle");
}





void cLuaState::Push(cLuaTCPLink * a_TCPLink)
{
	ASSERT(IsValid());

	tolua_pushusertype(m_LuaState, a_TCPLink, "cTCPLink");
}





void cLuaState::Push(cLuaUDPEndpoint * a_UDPEndpoint)
{
	ASSERT(IsValid());

	tolua_pushusertype(m_LuaState, a_UDPEndpoint, "cUDPEndpoint");
}





void cLuaState::Push(double a_Value)
{
	ASSERT(IsValid());

	tolua_pushnumber(m_LuaState, a_Value);
}





void cLuaState::Push(int a_Value)
{
	ASSERT(IsValid());

	tolua_pushnumber(m_LuaState, a_Value);
}





void cLuaState::Push(long a_Value)
{
	ASSERT(IsValid());

	tolua_pushnumber(m_LuaState, static_cast<lua_Number>(a_Value));
}





void cLuaState::Push(UInt32 a_Value)
{
	ASSERT(IsValid());

	tolua_pushnumber(m_LuaState, a_Value);
}





void cLuaState::Push(std::chrono::milliseconds a_Value)
{
	ASSERT(IsValid());

	tolua_pushnumber(m_LuaState, static_cast<lua_Number>(a_Value.count()));
}





void cLuaState::Pop(int a_NumValuesToPop)
{
	ASSERT(IsValid());

	lua_pop(m_LuaState, a_NumValuesToPop);
}





bool cLuaState::GetStackValue(int a_StackPos, AString & a_Value)
{
	size_t len = 0;
	const char * data = lua_tolstring(m_LuaState, a_StackPos, &len);
	if (data != nullptr)
	{
		a_Value.assign(data, len);
		return true;
	}
	return false;
}





bool cLuaState::GetStackValue(int a_StackPos, AStringMap & a_Value)
{
	// Retrieve all values in a string => string dictionary table:
	if (!lua_istable(m_LuaState, a_StackPos))
	{
		return false;
	}
	cStackTable tbl(*this, a_StackPos);
	bool isValid = true;
	tbl.ForEachElement([&isValid, &a_Value](cLuaState & a_LuaState)
		{
			AString key, val;
			if (a_LuaState.GetStackValues(-2, key, val))
			{
				a_Value[key] = val;
			}
			else
			{
				isValid = false;
				return true;
			}
			return false;
		}
	);
	return isValid;
}





bool cLuaState::GetStackValue(int a_StackPos, AStringVector & a_Value)
{
	// Retrieve all values in an array of string table:
	if (!lua_istable(m_LuaState, a_StackPos))
	{
		return false;
	}
	cStackTable tbl(*this, a_StackPos);
	bool isValid = true;
	tbl.ForEachArrayElement([&](cLuaState & a_LuaState, int a_Index)
		{
			AString tempStr;
			if (a_LuaState.GetStackValue(-1, tempStr))
			{
				a_Value.push_back(std::move(tempStr));
			}
			else
			{
				isValid = false;
				return true;
			}
			return false;
		}
	);
	return isValid;
}





bool cLuaState::GetStackValue(int a_StackPos, bool & a_ReturnedVal)
{
	a_ReturnedVal = (tolua_toboolean(m_LuaState, a_StackPos, a_ReturnedVal ? 1 : 0) > 0);
	return true;
}





bool cLuaState::GetStackValue(int a_StackPos, cCallback & a_Callback)
{
	return a_Callback.RefStack(*this, a_StackPos);
}





bool cLuaState::GetStackValue(int a_StackPos, cCallbackPtr & a_Callback)
{
	if (a_Callback == nullptr)
	{
		a_Callback = cpp14::make_unique<cCallback>();
	}
	return a_Callback->RefStack(*this, a_StackPos);
}





bool cLuaState::GetStackValue(int a_StackPos, cOptionalCallback & a_Callback)
{
	return a_Callback.RefStack(*this, a_StackPos);
}





bool cLuaState::GetStackValue(int a_StackPos, cOptionalCallbackPtr & a_Callback)
{
	if (a_Callback == nullptr)
	{
		a_Callback = cpp14::make_unique<cOptionalCallback>();
	}
	return a_Callback->RefStack(*this, a_StackPos);
}





bool cLuaState::GetStackValue(int a_StackPos, cCallbackSharedPtr & a_Callback)
{
	if (a_Callback == nullptr)
	{
		a_Callback = std::make_shared<cCallback>();
	}
	return a_Callback->RefStack(*this, a_StackPos);
}





bool cLuaState::GetStackValue(int a_StackPos, cPluginManager::CommandResult & a_Result)
{
	if (lua_isnumber(m_LuaState, a_StackPos))
	{
		a_Result = static_cast<cPluginManager::CommandResult>(static_cast<int>((tolua_tonumber(m_LuaState, a_StackPos, a_Result))));
		return true;
	}
	return false;
}





bool cLuaState::GetStackValue(int a_StackPos, cRef & a_Ref)
{
	a_Ref.RefStack(*this, a_StackPos);
	return true;
}





bool cLuaState::GetStackValue(int a_StackPos, cStackTablePtr & a_StackTable)
{
	// Only allow tables to be stored in a_StackTable:
	if (!lua_istable(m_LuaState, a_StackPos))
	{
		return false;
	}

	// Assign the StackTable to the specified stack position:
	a_StackTable = cpp14::make_unique<cStackTable>(*this, a_StackPos);
	return true;
}





bool cLuaState::GetStackValue(int a_StackPos, cTableRef & a_TableRef)
{
	return a_TableRef.RefStack(*this, a_StackPos);
}





bool cLuaState::GetStackValue(int a_StackPos, cTableRefPtr & a_TableRef)
{
	if (a_TableRef == nullptr)
	{
		a_TableRef = cpp14::make_unique<cTableRef>();
	}
	return a_TableRef->RefStack(*this, a_StackPos);
}





bool cLuaState::GetStackValue(int a_StackPos, cTrackedRef & a_Ref)
{
	return a_Ref.RefStack(*this, a_StackPos);
}





bool cLuaState::GetStackValue(int a_StackPos, cTrackedRefPtr & a_Ref)
{
	if (a_Ref == nullptr)
	{
		a_Ref = cpp14::make_unique<cTrackedRef>();
	}
	return a_Ref->RefStack(*this, a_StackPos);
}





bool cLuaState::GetStackValue(int a_StackPos, cTrackedRefSharedPtr & a_Ref)
{
	if (a_Ref == nullptr)
	{
		a_Ref = std::make_shared<cTrackedRef>();
	}
	return a_Ref->RefStack(*this, a_StackPos);
}





bool cLuaState::GetStackValue(int a_StackPos, double & a_ReturnedVal)
{
	if (lua_isnumber(m_LuaState, a_StackPos))
	{
		a_ReturnedVal = tolua_tonumber(m_LuaState, a_StackPos, a_ReturnedVal);
		return true;
	}
	return false;
}





bool cLuaState::GetStackValue(int a_StackPos, eBlockFace & a_ReturnedVal)
{
	if (!lua_isnumber(m_LuaState, a_StackPos))
	{
		return false;
	}
	a_ReturnedVal = static_cast<eBlockFace>(Clamp(
		static_cast<int>(tolua_tonumber(m_LuaState, a_StackPos, a_ReturnedVal)),
		static_cast<int>(BLOCK_FACE_MIN), static_cast<int>(BLOCK_FACE_MAX))
	);
	return true;
}





bool cLuaState::GetStackValue(int a_StackPos, eWeather & a_ReturnedVal)
{
	if (!lua_isnumber(m_LuaState, a_StackPos))
	{
		return false;
	}
	a_ReturnedVal = static_cast<eWeather>(Clamp(
		static_cast<int>(tolua_tonumber(m_LuaState, a_StackPos, a_ReturnedVal)),
		static_cast<int>(wSunny), static_cast<int>(wThunderstorm))
	);
	return true;
}





bool cLuaState::GetStackValue(int a_StackPos, float & a_ReturnedVal)
{
	if (lua_isnumber(m_LuaState, a_StackPos))
	{
		a_ReturnedVal = static_cast<float>(tolua_tonumber(m_LuaState, a_StackPos, a_ReturnedVal));
		return true;
	}
	return false;
}





bool cLuaState::GetStackValue(int a_StackPos, cUUID & a_Value)
{
	if (lua_isnil(m_LuaState, a_StackPos))
	{
		return false;
	}

	tolua_Error tolua_Err;
	if (tolua_isusertype(m_LuaState, a_StackPos, "cUUID", 0, &tolua_Err))
	{
		// Found a cUUID, copy into output value
		cUUID * PtrUUID = nullptr;
		GetStackValue(a_StackPos, PtrUUID);
		if (PtrUUID == nullptr)
		{
			return false;
		}
		a_Value = *PtrUUID;
		return true;
	}

	// Try to get a string and parse as a UUID into the output
	AString StrUUID;
	if (!GetStackValue(a_StackPos, StrUUID))
	{
		return false;
	}
	return a_Value.FromString(StrUUID);
}





template <typename T>
bool cLuaState::GetStackValue(int a_StackPos, Vector3<T> & a_ReturnedVal)
{
	tolua_Error err;
	if (lua_isnil(m_LuaState, a_StackPos))
	{
		return false;
	}
	if (tolua_isusertype(m_LuaState, a_StackPos, "Vector3<double>", 0, &err))
	{
		a_ReturnedVal = **(static_cast<const Vector3d **>(lua_touserdata(m_LuaState, a_StackPos)));
		return true;
	}
	if (tolua_isusertype(m_LuaState, a_StackPos, "Vector3<float>", 0, &err))
	{
		a_ReturnedVal = **(static_cast<const Vector3f **>(lua_touserdata(m_LuaState, a_StackPos)));
		return true;
	}
	if (tolua_isusertype(m_LuaState, a_StackPos, "Vector3<int>", 0, &err))
	{
		a_ReturnedVal = **(static_cast<const Vector3i **>(lua_touserdata(m_LuaState, a_StackPos)));
		return true;
	}

	// Bonus: Allow simple tables to work as Vector3:
	if (lua_istable(m_LuaState, a_StackPos))
	{
		lua_rawgeti(m_LuaState, a_StackPos, 1);
		lua_rawgeti(m_LuaState, a_StackPos, 2);
		lua_rawgeti(m_LuaState, a_StackPos, 3);
		T x, y, z;
		if (!GetStackValues(-3, x, y, z))
		{
			return false;
		}
		a_ReturnedVal = Vector3<T>(x, y, z);
		return true;
	}

	return false;
}

// Explicitly instantiate the previous function for all Vector3 types:
template bool cLuaState::GetStackValue(int a_StackPos, Vector3d & a_ReturnedVal);
template bool cLuaState::GetStackValue(int a_StackPos, Vector3f & a_ReturnedVal);
template bool cLuaState::GetStackValue(int a_StackPos, Vector3i & a_ReturnedVal);





cLuaState::cStackValue cLuaState::WalkToValue(const AString & a_Name)
{
	// There needs to be at least one value on the stack:
	ASSERT(lua_gettop(m_LuaState) > 0);

	// Iterate over path and replace the top of the stack with the walked element
	lua_pushvalue(m_LuaState, -1);  // Copy the stack value into the "working area"
	auto path = StringSplit(a_Name, ".");
	for (const auto & elem: path)
	{
		// If the value is not a table, bail out (error):
		if (!lua_istable(m_LuaState, -1))
		{
			lua_pop(m_LuaState, 1);
			return cStackValue();
		}

		// Get the next part of the path:
		lua_getfield(m_LuaState, -1, elem.c_str());

		// Remove the previous value from the stack (keep only the new one):
		lua_remove(m_LuaState, -2);
	}  // for elem - path[]
	if (lua_isnil(m_LuaState, -1))
	{
		lua_pop(m_LuaState, 1);
		return cStackValue();
	}
	return cStackValue(*this);
}





cLuaState::cStackValue cLuaState::WalkToNamedGlobal(const AString & a_Name)
{
	// Iterate over path and replace the top of the stack with the walked element
	lua_getglobal(m_LuaState, "_G");
	auto path = StringSplit(a_Name, ".");
	for (const auto & elem: path)
	{
		// If the value is not a table, bail out (error):
		if (!lua_istable(m_LuaState, -1))
		{
			lua_pop(m_LuaState, 1);
			return cStackValue();
		}

		// Get the next part of the path:
		lua_getfield(m_LuaState, -1, elem.c_str());

		// Remove the previous value from the stack (keep only the new one):
		lua_remove(m_LuaState, -2);
	}  // for elem - path[]
	if (lua_isnil(m_LuaState, -1))
	{
		lua_pop(m_LuaState, 1);
		return cStackValue();
	}
	return cStackValue(*this);
}





bool cLuaState::CallFunction(int a_NumResults)
{
	ASSERT (m_NumCurrentFunctionArgs >= 0);  // A function must be pushed to stack first
	ASSERT(lua_isfunction(m_LuaState, -m_NumCurrentFunctionArgs - 1));  // The function to call
	ASSERT(lua_isfunction(m_LuaState, -m_NumCurrentFunctionArgs - 2));  // The error handler

	// Save the current "stack" state and reset, in case the callback calls another function:
	AString CurrentFunctionName;
	std::swap(m_CurrentFunctionName, CurrentFunctionName);
	int NumArgs = m_NumCurrentFunctionArgs;
	m_NumCurrentFunctionArgs = -1;

	// Call the function:
	int s = lua_pcall(m_LuaState, NumArgs, a_NumResults, -NumArgs - 2);
	if (s != 0)
	{
		// The error has already been printed together with the stacktrace
		LOGWARNING("Error in %s calling function %s()", m_SubsystemName.c_str(), CurrentFunctionName.c_str());

		// Remove the error handler and error message from the stack:
		auto top = lua_gettop(m_LuaState);
		if (top < 2)
		{
			LogStackValues(Printf("The Lua stack is in an unexpected state, expected at least two values there, but got %d", top).c_str());
		}
		lua_pop(m_LuaState, std::min(2, top));
		return false;
	}

	// Remove the error handler from the stack:
	lua_remove(m_LuaState, -a_NumResults - 1);
	return true;
}





bool cLuaState::CheckParamUserTable(int a_StartParam, const char * a_UserTable, int a_EndParam)
{
	ASSERT(IsValid());

	if (a_EndParam < 0)
	{
		a_EndParam = a_StartParam;
	}

	tolua_Error tolua_err;
	for (int i = a_StartParam; i <= a_EndParam; i++)
	{
		if (tolua_isusertable(m_LuaState, i, a_UserTable, 0, &tolua_err))
		{
			continue;
		}
		// Not the correct parameter
		lua_Debug entry;
		VERIFY(lua_getstack(m_LuaState, 0,   &entry));
		VERIFY(lua_getinfo (m_LuaState, "n", &entry));
		AString ErrMsg = Printf("#ferror in function '%s'.", (entry.name != nullptr) ? entry.name : "?");
		tolua_error(m_LuaState, ErrMsg.c_str(), &tolua_err);
		return false;
	}  // for i - Param

	// All params checked ok
	return true;
}





bool cLuaState::CheckParamUserType(int a_StartParam, const char * a_UserType, int a_EndParam)
{
	ASSERT(IsValid());

	if (a_EndParam < 0)
	{
		a_EndParam = a_StartParam;
	}

	tolua_Error tolua_err;
	for (int i = a_StartParam; i <= a_EndParam; i++)
	{
		if (tolua_isusertype(m_LuaState, i, a_UserType, 0, &tolua_err))
		{
			continue;
		}
		// Not the correct parameter
		lua_Debug entry;
		VERIFY(lua_getstack(m_LuaState, 0,   &entry));
		VERIFY(lua_getinfo (m_LuaState, "n", &entry));
		AString ErrMsg = Printf("#ferror in function '%s'.", (entry.name != nullptr) ? entry.name : "?");
		tolua_error(m_LuaState, ErrMsg.c_str(), &tolua_err);
		return false;
	}  // for i - Param

	// All params checked ok
	return true;
}





bool cLuaState::CheckParamTable(int a_StartParam, int a_EndParam)
{
	ASSERT(IsValid());

	if (a_EndParam < 0)
	{
		a_EndParam = a_StartParam;
	}

	tolua_Error tolua_err;
	for (int i = a_StartParam; i <= a_EndParam; i++)
	{
		if (tolua_istable(m_LuaState, i, 0, &tolua_err))
		{
			continue;
		}
		// Not the correct parameter
		lua_Debug entry;
		VERIFY(lua_getstack(m_LuaState, 0,   &entry));
		VERIFY(lua_getinfo (m_LuaState, "n", &entry));
		AString ErrMsg = Printf("#ferror in function '%s'.", (entry.name != nullptr) ? entry.name : "?");

		BreakIntoDebugger(m_LuaState);

		tolua_error(m_LuaState, ErrMsg.c_str(), &tolua_err);
		return false;
	}  // for i - Param

	// All params checked ok
	return true;
}





bool cLuaState::CheckParamNumber(int a_StartParam, int a_EndParam)
{
	ASSERT(IsValid());

	if (a_EndParam < 0)
	{
		a_EndParam = a_StartParam;
	}

	tolua_Error tolua_err;
	for (int i = a_StartParam; i <= a_EndParam; i++)
	{
		if (tolua_isnumber(m_LuaState, i, 0, &tolua_err))
		{
			continue;
		}
		// Not the correct parameter
		lua_Debug entry;
		VERIFY(lua_getstack(m_LuaState, 0,   &entry));
		VERIFY(lua_getinfo (m_LuaState, "n", &entry));
		AString ErrMsg = Printf("#ferror in function '%s'.", (entry.name != nullptr) ? entry.name : "?");
		tolua_error(m_LuaState, ErrMsg.c_str(), &tolua_err);
		return false;
	}  // for i - Param

	// All params checked ok
	return true;
}





bool cLuaState::CheckParamBool(int a_StartParam, int a_EndParam)
{
	ASSERT(IsValid());

	if (a_EndParam < 0)
	{
		a_EndParam = a_StartParam;
	}

	tolua_Error tolua_err;
	for (int i = a_StartParam; i <= a_EndParam; i++)
	{
		if (tolua_isboolean(m_LuaState, i, 0, &tolua_err))
		{
			continue;
		}
		// Not the correct parameter
		lua_Debug entry;
		VERIFY(lua_getstack(m_LuaState, 0,   &entry));
		VERIFY(lua_getinfo (m_LuaState, "n", &entry));
		AString ErrMsg = Printf("#ferror in function '%s'.", (entry.name != nullptr) ? entry.name : "?");
		tolua_error(m_LuaState, ErrMsg.c_str(), &tolua_err);
		return false;
	}  // for i - Param

	// All params checked ok
	return true;
}





bool cLuaState::CheckParamString(int a_StartParam, int a_EndParam)
{
	ASSERT(IsValid());

	if (a_EndParam < 0)
	{
		a_EndParam = a_StartParam;
	}

	tolua_Error tolua_err;
	for (int i = a_StartParam; i <= a_EndParam; i++)
	{
		if (lua_isstring(m_LuaState, i))
		{
			continue;
		}
		// Not the correct parameter
		lua_Debug entry;
		VERIFY(lua_getstack(m_LuaState, 0,   &entry));
		VERIFY(lua_getinfo (m_LuaState, "n", &entry));
		tolua_err.array = 0;
		tolua_err.type = "string";
		tolua_err.index = i;
		AString ErrMsg = Printf("#ferror in function '%s'.", (entry.name != nullptr) ? entry.name : "?");
		tolua_error(m_LuaState, ErrMsg.c_str(), &tolua_err);
		return false;
	}  // for i - Param

	// All params checked ok
	return true;
}





bool cLuaState::CheckParamFunction(int a_StartParam, int a_EndParam)
{
	ASSERT(IsValid());

	if (a_EndParam < 0)
	{
		a_EndParam = a_StartParam;
	}

	for (int i = a_StartParam; i <= a_EndParam; i++)
	{
		if (lua_isfunction(m_LuaState, i))
		{
			continue;
		}
		// Not the correct parameter
		lua_Debug entry;
		VERIFY(lua_getstack(m_LuaState, 0,   &entry));
		VERIFY(lua_getinfo (m_LuaState, "n", &entry));
		luaL_error(m_LuaState, "Error in function '%s' parameter #%d. Function expected, got %s",
			(entry.name != nullptr) ? entry.name : "?", i, GetTypeText(i).c_str()
		);
		return false;
	}  // for i - Param

	// All params checked ok
	return true;
}





bool cLuaState::CheckParamFunctionOrNil(int a_StartParam, int a_EndParam)
{
	ASSERT(IsValid());

	if (a_EndParam < 0)
	{
		a_EndParam = a_StartParam;
	}

	for (int i = a_StartParam; i <= a_EndParam; i++)
	{
		if (lua_isfunction(m_LuaState, i) || lua_isnil(m_LuaState, i))
		{
			continue;
		}
		// Not the correct parameter
		lua_Debug entry;
		VERIFY(lua_getstack(m_LuaState, 0,   &entry));
		VERIFY(lua_getinfo (m_LuaState, "n", &entry));
		luaL_error(m_LuaState, "Error in function '%s' parameter #%d. Function expected, got %s",
			(entry.name != nullptr) ? entry.name : "?", i, GetTypeText(i).c_str()
		);
		return false;
	}  // for i - Param

	// All params checked ok
	return true;
}





bool cLuaState::CheckParamUUID(int a_StartParam, int a_EndParam)
{
	ASSERT(IsValid());

	if (a_EndParam < 0)
	{
		a_EndParam = a_StartParam;
	}

	cUUID tempUUID;
	AString tempStr;
	// Accept either a cUUID or a string that contains a valid UUID
	for (int i = a_StartParam; i <= a_EndParam; ++i)
	{
		tolua_Error err;
		if (tolua_isusertype(m_LuaState, i, "cUUID", 0, &err) && !lua_isnil(m_LuaState, i))
		{
			continue;
		}

		if (!tolua_iscppstring(m_LuaState, i, 0, &err))
		{
			ApiParamError("Failed to read parameter #%d. UUID expected, got %s", i, GetTypeText(i).c_str());
			return false;
		}

		// Check string is a valid UUID
		GetStackValue(i, tempStr);
		if (!tempUUID.FromString(tempStr))
		{
			ApiParamError("Failed to read parameter #%d. UUID expected, got non-UUID string:\n\t\"%s\"", i, tempStr.c_str());
			return false;
		}
	}
	return true;
}





bool cLuaState::CheckParamEnd(int a_Param)
{
	tolua_Error tolua_err;
	if (tolua_isnoobj(m_LuaState, a_Param, &tolua_err) == 1)
	{
		return true;
	}
	// Not the correct parameter
	lua_Debug entry;
	VERIFY(lua_getstack(m_LuaState, 0,   &entry));
	VERIFY(lua_getinfo (m_LuaState, "n", &entry));
	AString ErrMsg = Printf("#ferror in function '%s': Too many arguments.", (entry.name != nullptr) ? entry.name : "?");
	tolua_error(m_LuaState, ErrMsg.c_str(), &tolua_err);
	return false;
}





bool cLuaState::CheckParamSelf(const char * a_SelfClassName)
{
	tolua_Error tolua_err;
	if (tolua_isusertype(m_LuaState, 1, a_SelfClassName, 0, &tolua_err) && !lua_isnil(m_LuaState, 1))
	{
		return true;
	}

	// Not the correct parameter
	lua_Debug entry;
	VERIFY(lua_getstack(m_LuaState, 0,   &entry));
	VERIFY(lua_getinfo (m_LuaState, "n", &entry));
	AString ErrMsg = Printf(
		"Error in function '%s'. The 'self' parameter is not of the expected type, \"instance of %s\". " \
		"Make sure you're using the correct calling convention (obj:fn() instead of obj.fn()).",
		(entry.name != nullptr) ? entry.name : "<unknown>", a_SelfClassName
	);
	tolua_error(m_LuaState, ErrMsg.c_str(), &tolua_err);
	return false;
}





bool cLuaState::CheckParamStaticSelf(const char * a_SelfClassName)
{
	tolua_Error tolua_err;
	if (tolua_isusertable(m_LuaState, 1, a_SelfClassName, 0, &tolua_err) && !lua_isnil(m_LuaState, 1))
	{
		return true;
	}

	// Not the correct parameter
	lua_Debug entry;
	VERIFY(lua_getstack(m_LuaState, 0,   &entry));
	VERIFY(lua_getinfo (m_LuaState, "n", &entry));
	AString ErrMsg = Printf(
		"Error in function '%s'. The 'self' parameter is not of the expected type, \"class %s\". " \
		"Make sure you're using the correct calling convention (cClassName:fn() instead of cClassName.fn() or obj:fn()).",
		(entry.name != nullptr) ? entry.name : "<unknown>", a_SelfClassName
	);
	tolua_error(m_LuaState, ErrMsg.c_str(), &tolua_err);
	return false;
}





bool cLuaState::IsParamUserType(int a_ParamIdx, AString a_UserType)
{
	ASSERT(IsValid());

	tolua_Error tolua_err;
	return (tolua_isusertype(m_LuaState, a_ParamIdx, a_UserType.c_str(), 0, &tolua_err) == 1);
}





bool cLuaState::IsParamNumber(int a_ParamIdx)
{
	ASSERT(IsValid());

	tolua_Error tolua_err;
	return (tolua_isnumber(m_LuaState, a_ParamIdx, 0, &tolua_err) == 1);
}





bool cLuaState::IsParamVector3(int a_ParamIdx)
{
	ASSERT(IsValid());

	return (
		IsParamUserType(a_ParamIdx, "Vector3<double>") ||
		IsParamUserType(a_ParamIdx, "Vector3<float>") ||
		IsParamUserType(a_ParamIdx, "Vector3<int>") ||
		lua_istable(m_LuaState, a_ParamIdx)  // Assume any table is good enough
	);
}





bool cLuaState::ReportErrors(int a_Status)
{
	return ReportErrors(m_LuaState, a_Status);
}





bool cLuaState::ReportErrors(lua_State * a_LuaState, int a_Status)
{
	if (a_Status == 0)
	{
		// No error to report
		return false;
	}

	LOGWARNING("LUA: %d - %s", a_Status, lua_tostring(a_LuaState, -1));
	lua_pop(a_LuaState, 1);
	return true;
}





void cLuaState::LogStackTrace(int a_StartingDepth)
{
	LogStackTrace(m_LuaState, a_StartingDepth);
}





void cLuaState::LogStackTrace(lua_State * a_LuaState, int a_StartingDepth)
{
	LOGWARNING("Stack trace:");
	lua_Debug entry;
	int depth = a_StartingDepth;
	while (lua_getstack(a_LuaState, depth, &entry))
	{
		lua_getinfo(a_LuaState, "Sln", &entry);
		LOGWARNING("  %s(%d): %s", entry.short_src, entry.currentline, entry.name ? entry.name : "(no name)");
		depth++;
	}
	LOGWARNING("Stack trace end");
}





int cLuaState::ApiParamError(fmt::StringRef a_Msg)
{
	// Retrieve current function name
	lua_Debug entry;
	VERIFY(lua_getstack(m_LuaState, 0, &entry));
	VERIFY(lua_getinfo(m_LuaState, "n", &entry));

	// Compose the error message:
	AString errorMsg = fmt::format("{0}: {1}", (entry.name != nullptr) ? entry.name : "<unknown function>", a_Msg);

	// Log everything into the console:
	LOGWARNING("%s", errorMsg.c_str());
	// cLuaState::LogStackTrace(a_LuaState);  // Do NOT log stack trace, it is already output as part of the Lua error handling
	LogStackValues(m_LuaState, "Parameters on the stack");

	// Raise Lua error:
	lua_pushstring(m_LuaState, errorMsg.c_str());
	return lua_error(m_LuaState);
}





AString cLuaState::GetTypeText(int a_StackPos)
{
	return lua_typename(m_LuaState, lua_type(m_LuaState, a_StackPos));
}





int cLuaState::CallFunctionWithForeignParams(
	const AString & a_FunctionName,
	cLuaState & a_SrcLuaState,
	int a_SrcParamStart,
	int a_SrcParamEnd
)
{
	ASSERT(IsValid());
	ASSERT(a_SrcLuaState.IsValid());

	// Store the stack position before any changes
	int OldTop = lua_gettop(m_LuaState);

	// Push the function to call, including the error handler:
	if (!PushFunction(a_FunctionName.c_str()))
	{
		LOGWARNING("Function '%s' not found", a_FunctionName.c_str());
		lua_settop(m_LuaState, OldTop);
		return -1;
	}

	// Copy the function parameters to the target state
	if (CopyStackFrom(a_SrcLuaState, a_SrcParamStart, a_SrcParamEnd) < 0)
	{
		// Something went wrong, fix the stack and exit
		lua_settop(m_LuaState, OldTop);
		m_NumCurrentFunctionArgs = -1;
		m_CurrentFunctionName.clear();
		return -1;
	}

	// Call the function, with an error handler:
	int s = lua_pcall(m_LuaState, a_SrcParamEnd - a_SrcParamStart + 1, LUA_MULTRET, OldTop + 1);
	if (ReportErrors(s))
	{
		LOGWARN("Error while calling function '%s' in '%s'", a_FunctionName.c_str(), m_SubsystemName.c_str());
		// Reset the stack:
		lua_settop(m_LuaState, OldTop);

		// Reset the internal checking mechanisms:
		m_NumCurrentFunctionArgs = -1;
		m_CurrentFunctionName.clear();

		// Make Lua think everything is okay and return 0 values, so that plugins continue executing.
		// The failure is indicated by the zero return values.
		return 0;
	}

	// Reset the internal checking mechanisms:
	m_NumCurrentFunctionArgs = -1;
	m_CurrentFunctionName.clear();

	// Remove the error handler from the stack:
	lua_remove(m_LuaState, OldTop + 1);

	// Return the number of return values:
	return lua_gettop(m_LuaState) - OldTop;
}





int cLuaState::CopyStackFrom(cLuaState & a_SrcLuaState, int a_SrcStart, int a_SrcEnd, int a_NumAllowedNestingLevels)
{
	/*
	// DEBUG:
	LOGD("Copying stack values from %d to %d", a_SrcStart, a_SrcEnd);
	a_SrcLuaState.LogStack("Src stack before copying:");
	LogStack("Dst stack before copying:");
	*/
	for (int i = a_SrcStart; i <= a_SrcEnd; ++i)
	{
		if (!CopySingleValueFrom(a_SrcLuaState, i, a_NumAllowedNestingLevels))
		{
			lua_pop(m_LuaState, i - a_SrcStart);
			return -1;
		}
	}
	return a_SrcEnd - a_SrcStart + 1;
}





bool cLuaState::CopyTableFrom(cLuaState & a_SrcLuaState, int a_SrcStackIdx, int a_NumAllowedNestingLevels)
{
	// Create the dest table:
	#ifdef _DEBUG
		auto srcTop = lua_gettop(a_SrcLuaState);
		auto dstTop = lua_gettop(m_LuaState);
	#endif
	lua_createtable(m_LuaState, 0, 0);            // DST: <table>
	lua_pushvalue(a_SrcLuaState, a_SrcStackIdx);  // SRC: <table>
	lua_pushnil(a_SrcLuaState);                   // SRC: <table> <key>
	while (lua_next(a_SrcLuaState, -2) != 0)      // SRC: <table> <key> <value>
	{
		ASSERT(lua_gettop(a_SrcLuaState) == srcTop + 3);
		ASSERT(lua_gettop(m_LuaState) == dstTop + 1);

		// Copy the key:
		if (!CopySingleValueFrom(a_SrcLuaState, -2, a_NumAllowedNestingLevels))  // DST: <table> <key>
		{
			lua_pop(m_LuaState, 1);
			lua_pop(a_SrcLuaState, 3);
			ASSERT(lua_gettop(a_SrcLuaState) == srcTop);
			ASSERT(lua_gettop(m_LuaState) == dstTop);
			return false;
		}
		ASSERT(lua_gettop(a_SrcLuaState) == srcTop + 3);
		ASSERT(lua_gettop(m_LuaState) == dstTop + 2);

		// Copy the value:
		if (!CopySingleValueFrom(a_SrcLuaState, -1, a_NumAllowedNestingLevels - 1))  // DST: <table> <key> <value>
		{
			lua_pop(m_LuaState, 2);     // DST: empty
			lua_pop(a_SrcLuaState, 3);  // SRC: empty
			ASSERT(lua_gettop(a_SrcLuaState) == srcTop);
			ASSERT(lua_gettop(m_LuaState) == dstTop);
			return false;
		}
		ASSERT(lua_gettop(a_SrcLuaState) == srcTop + 3);
		ASSERT(lua_gettop(m_LuaState) == dstTop + 3);

		// Set the value and fix up stacks:
		lua_rawset(m_LuaState, -3);  // DST: <table>
		lua_pop(a_SrcLuaState, 1);  // SRC: <table> <key>
		ASSERT(lua_gettop(a_SrcLuaState) == srcTop + 2);
		ASSERT(lua_gettop(m_LuaState) == dstTop + 1);
	}
	lua_pop(a_SrcLuaState, 1);  // SRC: empty
	ASSERT(lua_gettop(a_SrcLuaState) == srcTop);
	ASSERT(lua_gettop(m_LuaState) == dstTop + 1);
	return true;
}





bool cLuaState::CopySingleValueFrom(cLuaState & a_SrcLuaState, int a_StackIdx, int a_NumAllowedNestingLevels)
{
	int t = lua_type(a_SrcLuaState, a_StackIdx);
	switch (t)
	{
		case LUA_TNIL:
		{
			lua_pushnil(m_LuaState);
			return true;
		}
		case LUA_TSTRING:
		{
			AString s;
			a_SrcLuaState.ToString(a_StackIdx, s);
			Push(s);
			return true;
		}
		case LUA_TBOOLEAN:
		{
			bool b = (tolua_toboolean(a_SrcLuaState, a_StackIdx, false) != 0);
			Push(b);
			return true;
		}
		case LUA_TNUMBER:
		{
			lua_Number d = tolua_tonumber(a_SrcLuaState, a_StackIdx, 0);
			Push(d);
			return true;
		}
		case LUA_TUSERDATA:
		{
			// Get the class name:
			const char * type = nullptr;
			if (lua_getmetatable(a_SrcLuaState, a_StackIdx) == 0)
			{
				LOGWARNING("%s: Unknown class in pos %d, cannot copy.", __FUNCTION__, a_StackIdx);
				return false;
			}
			lua_rawget(a_SrcLuaState, LUA_REGISTRYINDEX);  // Stack +1
			type = lua_tostring(a_SrcLuaState, -1);
			lua_pop(a_SrcLuaState, 1);                     // Stack -1

			// Copy the value:
			void * ud = tolua_touserdata(a_SrcLuaState, a_StackIdx, nullptr);
			tolua_pushusertype(m_LuaState, ud, type);
			return true;
		}
		case LUA_TTABLE:
		{
			if (!CopyTableFrom(a_SrcLuaState, a_StackIdx, a_NumAllowedNestingLevels - 1))
			{
				LOGWARNING("%s: Failed to copy table in pos %d.", __FUNCTION__, a_StackIdx);
				return false;
			}
			return true;
		}
		default:
		{
			LOGWARNING("%s: Unsupported value: '%s' at stack position %d. Can only copy numbers, strings, bools, classes and simple tables!",
				__FUNCTION__, lua_typename(a_SrcLuaState, t), a_StackIdx
			);
			return false;
		}
	}
}





void cLuaState::ToString(int a_StackPos, AString & a_String)
{
	size_t len;
	const char * s = lua_tolstring(m_LuaState, a_StackPos, &len);
	if (s != nullptr)
	{
		a_String.assign(s, len);
	}
}





void cLuaState::LogStackValues(const char * a_Header)
{
	LogStackValues(m_LuaState, a_Header);
}





void cLuaState::LogStackValues(lua_State * a_LuaState, const char * a_Header)
{
	// Format string consisting only of %s is used to appease the compiler
	ASSERT_LUA_STACK_BALANCE(a_LuaState, false);
	LOG("%s", (a_Header != nullptr) ? a_Header : "Lua C API Stack contents:");
	for (int i = lua_gettop(a_LuaState); i > 0; i--)
	{
		AString Value;
		int Type = lua_type(a_LuaState, i);
		switch (Type)
		{
			case LUA_TBOOLEAN: Value.assign((lua_toboolean(a_LuaState, i) != 0) ? "true" : "false"); break;
			case LUA_TLIGHTUSERDATA: Printf(Value, "%p", lua_touserdata(a_LuaState, i)); break;
			case LUA_TNUMBER:        Printf(Value, "%f", static_cast<double>(lua_tonumber(a_LuaState, i))); break;
			case LUA_TSTRING:
			{
				size_t len;
				const char * txt = lua_tolstring(a_LuaState, i, &len);
				Value.assign(txt, std::min<size_t>(len, 50));  // Only log up to 50 characters of the string
				break;
			}
			case LUA_TTABLE:         Printf(Value, "%p", lua_topointer(a_LuaState, i)); break;
			case LUA_TFUNCTION:      Printf(Value, "%p", lua_topointer(a_LuaState, i)); break;
			case LUA_TUSERDATA:
			{
				Printf(Value, "%p (%s)", lua_touserdata(a_LuaState, i), tolua_typename(a_LuaState, i));
				// tolua_typename pushes the string onto Lua stack, pop it off again:
				lua_pop(a_LuaState, 1);
				break;
			}
			default: break;
		}
		LOGD("  Idx %d: type %d (%s) %s", i, Type, lua_typename(a_LuaState, Type), Value.c_str());
	}  // for i - stack idx
}





cLuaState * cLuaState::QueryCanonLuaState(void) const
{
	return cCanonLuaStates::GetCanonState(m_LuaState);
}





void cLuaState::LogApiCallParamFailure(const char * a_FnName, const char * a_ParamNames)
{
	LOGWARNING("%s: Cannot read params: %s, bailing out.", a_FnName, a_ParamNames);
	LogStackTrace();
	LogStackValues("Values on the stack");
}





void cLuaState::TrackInDeadlockDetect(cDeadlockDetect & a_DeadlockDetect)
{
	a_DeadlockDetect.TrackCriticalSection(m_CS, Printf("cLuaState %s", m_SubsystemName.c_str()));
}





void cLuaState::UntrackInDeadlockDetect(cDeadlockDetect & a_DeadlockDetect)
{
	a_DeadlockDetect.UntrackCriticalSection(m_CS);
}





int cLuaState::ReportFnCallErrors(lua_State * a_LuaState)
{
	LOGWARNING("LUA: %s", lua_tostring(a_LuaState, -1));
	LogStackTrace(a_LuaState, 1);
	BreakIntoDebugger(a_LuaState);
	return 1;  // We left the error message on the stack as the return value
}





int cLuaState::BreakIntoDebugger(lua_State * a_LuaState)
{
	ASSERT_LUA_STACK_BALANCE(a_LuaState);
	// Call the BreakIntoDebugger function, if available:
	lua_getglobal(a_LuaState, "BreakIntoDebugger");
	if (!lua_isfunction(a_LuaState, -1))
	{
		LOGD("LUA: BreakIntoDebugger() not found / not a function");
		lua_pop(a_LuaState, 1);
		return 1;
	}
	lua_pushvalue(a_LuaState, -2);  // Copy the string that has been passed to us
	LOGD("Calling BreakIntoDebugger()...");
	lua_call(a_LuaState, 1, 0);
	LOGD("Returned from BreakIntoDebugger().");
	return 0;
}





void cLuaState::TrackRef(cTrackedRef & a_Ref)
{
	// Get the CanonLuaState global from Lua:
	auto canonState = QueryCanonLuaState();
	if (canonState == nullptr)
	{
		LOGWARNING("%s: Lua state %p has invalid CanonLuaState!", __FUNCTION__, static_cast<void *>(m_LuaState));
		return;
	}

	// Add the callback:
	cCSLock Lock(canonState->m_CSTrackedRefs);
	canonState->m_TrackedRefs.push_back(&a_Ref);
}





void cLuaState::UntrackRef(cTrackedRef & a_Ref)
{
	// Get the CanonLuaState global from Lua:
	auto canonState = QueryCanonLuaState();
	if (canonState == nullptr)
	{
		LOGWARNING("%s: Lua state %p has invalid CanonLuaState!", __FUNCTION__, static_cast<void *>(m_LuaState));
		return;
	}

	// Remove the callback (note that another thread may have cleared the callbacks by closing the LuaState):
	cCSLock Lock(canonState->m_CSTrackedRefs);
	auto & trackedRefs = canonState->m_TrackedRefs;
	for (auto itr = trackedRefs.begin(), end = trackedRefs.end(); itr != end; ++itr)
	{
		if (*itr == &a_Ref)
		{
			trackedRefs.erase(itr);
			break;
		}
	}
}





////////////////////////////////////////////////////////////////////////////////
// cLuaState::cRef:

cLuaState::cRef::cRef(void) :
	m_LuaState(nullptr),
	m_Ref(LUA_REFNIL)
{
}





cLuaState::cRef::cRef(cLuaState & a_LuaState, int a_StackPos) :
	m_LuaState(nullptr),
	m_Ref(LUA_REFNIL)
{
	RefStack(a_LuaState, a_StackPos);
}





cLuaState::cRef::cRef(cRef && a_FromRef):
	m_LuaState(a_FromRef.m_LuaState),
	m_Ref(a_FromRef.m_Ref)
{
	a_FromRef.m_LuaState = nullptr;
	a_FromRef.m_Ref = LUA_REFNIL;
}





cLuaState::cRef::~cRef()
{
	if (m_LuaState != nullptr)
	{
		UnRef();
	}
}





void cLuaState::cRef::RefStack(cLuaState & a_LuaState, int a_StackPos)
{
	ASSERT(a_LuaState.IsValid());
	if (m_LuaState != nullptr)
	{
		UnRef();
	}
	ASSERT(cCanonLuaStates::GetCanonState(a_LuaState)->m_CS.IsLockedByCurrentThread());
	m_LuaState = a_LuaState;
	lua_pushvalue(a_LuaState, a_StackPos);  // Push a copy of the value at a_StackPos onto the stack
	m_Ref = luaL_ref(a_LuaState, LUA_REGISTRYINDEX);
}





void cLuaState::cRef::UnRef(void)
{
	if (IsValid())
	{
		ASSERT(cCanonLuaStates::GetCanonState(m_LuaState)->m_CS.IsLockedByCurrentThread());
		luaL_unref(m_LuaState, LUA_REGISTRYINDEX, m_Ref);
	}
	m_LuaState = nullptr;
	m_Ref = LUA_REFNIL;
}