summaryrefslogtreecommitdiffstatshomepage
path: root/src/frontend/mame/luaengine.cpp
blob: d0fdcedab881b0a32fb0a5397c0e2e289f27dcf2 (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
// license:BSD-3-Clause
// copyright-holders:Miodrag Milanovic,Luca Bruno
/***************************************************************************

    luaengine.cpp

    Controls execution of the core MAME system.

***************************************************************************/

#include "emu.h"
#include "luaengine.ipp"

#include "mame.h"
#include "pluginopts.h"
#include "ui/pluginopt.h"
#include "ui/ui.h"

#include "imagedev/cassette.h"

#include "debugger.h"
#include "drivenum.h"
#include "emuopts.h"
#include "inputdev.h"
#include "natkeyboard.h"
#include "softlist.h"
#include "uiinput.h"

#include <cstring>
#include <thread>


//**************************************************************************
//  LUA ENGINE
//**************************************************************************

extern "C" {

int luaopen_zlib(lua_State *L);
int luaopen_lfs(lua_State *L);
int luaopen_linenoise(lua_State *L);
int luaopen_lsqlite3(lua_State *L);

} // extern "C"


template <typename T>
struct lua_engine::devenum
{
	devenum(device_t &d) : device(d), iter(d) { }

	device_t &device;
	T iter;
	int count = -1;
};


namespace sol
{

sol::buffer *sol_lua_get(sol::types<buffer *>, lua_State *L, int index, sol::stack::record &tracking)
{
	return new sol::buffer(stack::get<int>(L, index), L);
}

int sol_lua_push(sol::types<buffer *>, lua_State *L, buffer *value)
{
	delete value;
	return 1;
}

template <typename T>
struct usertype_container<lua_engine::devenum<T> > : lua_engine::immutable_container_helper<lua_engine::devenum<T>, T>
{
private:
	using enumerator = lua_engine::devenum<T>;

	template <bool Indexed>
	static int next_pairs(lua_State *L)
	{
		typename usertype_container::indexed_iterator &i(stack::unqualified_get<user<typename usertype_container::indexed_iterator> >(L, 1));
		if (i.src.end() == i.it)
			return stack::push(L, lua_nil);
		int result;
		if constexpr (Indexed)
			result = stack::push(L, i.ix + 1);
		else
			result = stack::push(L, i.it->tag());
		result += stack::push_reference(L, *i.it);
		++i;
		return result;
	}

	template <bool Indexed>
	static int start_pairs(lua_State *L)
	{
		enumerator &self(usertype_container::get_self(L));
		stack::push(L, next_pairs<Indexed>);
		stack::push<user<typename usertype_container::indexed_iterator> >(L, self.iter, self.iter.begin());
		stack::push(L, lua_nil);
		return 3;
	}

public:
	static int at(lua_State *L)
	{
		enumerator &self(usertype_container::get_self(L));
		std::ptrdiff_t const index(stack::unqualified_get<std::ptrdiff_t>(L, 2));
		auto const dev(self.iter.byindex(index - 1));
		if (dev)
			return stack::push_reference(L, *dev);
		else
			return stack::push(L, lua_nil);
	}

	static int get(lua_State *L)
	{
		enumerator &self(usertype_container::get_self(L));
		char const *const tag(stack::unqualified_get<char const *>(L));
		device_t *const dev(self.device.subdevice(tag));
		if (dev)
		{
			auto *const check(T(*dev, 0).first());
			bool match;
			if constexpr (std::is_base_of_v<device_t, decltype(*check)>)
				match = check && (static_cast<device_t *>(check) == dev);
			else if constexpr (std::is_base_of_v<device_interface, decltype(*check)>)
				match = check && (&check->device() == dev);
			else
				match = check && (dynamic_cast<device_t *>(check) == dev);
			if (match)
				return stack::push_reference(L, *check);
		}
		return stack::push(L, lua_nil);
	}

	static int index_get(lua_State *L)
	{
		return get(L);
	}

	static int index_of(lua_State *L)
	{
		enumerator &self(usertype_container::get_self(L));
		auto &dev(stack::unqualified_get<decltype(*self.iter.first())>(L, 2));
		std::ptrdiff_t found(self.iter.indexof(dev));
		if (0 > found)
			return stack::push(L, lua_nil);
		else
			return stack::push(L, found + 1);
	}

	static int size(lua_State *L)
	{
		enumerator &self(usertype_container::get_self(L));
		if (0 > self.count)
			self.count = self.iter.count();
		return stack::push(L, self.count);
	}

	static int empty(lua_State *L)
	{
		enumerator &self(usertype_container::get_self(L));
		if (0 > self.count)
			self.count = self.iter.count();
		return stack::push(L, !self.count);
	}

	static int next(lua_State *L) { return stack::push(L, next_pairs<false>); }
	static int pairs(lua_State *L) { return start_pairs<false>(L); }
	static int ipairs(lua_State *L) { return start_pairs<true>(L); }
};

} // namespace sol


int sol_lua_push(sol::types<osd_file::error>, lua_State *L, osd_file::error &&value)
{
	const char *strerror;
	switch(value)
	{
		case osd_file::error::NONE:
			return sol::stack::push(L, sol::lua_nil);
		case osd_file::error::FAILURE:
			strerror = "failure";
			break;
		case osd_file::error::OUT_OF_MEMORY:
			strerror = "out_of_memory";
			break;
		case osd_file::error::NOT_FOUND:
			strerror = "not_found";
			break;
		case osd_file::error::ACCESS_DENIED:
			strerror = "access_denied";
			break;
		case osd_file::error::ALREADY_OPEN:
			strerror = "already_open";
			break;
		case osd_file::error::TOO_MANY_FILES:
			strerror = "too_many_files";
			break;
		case osd_file::error::INVALID_DATA:
			strerror = "invalid_data";
			break;
		case osd_file::error::INVALID_ACCESS:
			strerror = "invalid_access";
			break;
		default:
			strerror = "unknown_error";
			break;
	}
	return sol::stack::push(L, strerror);
}

template <typename Handler>
bool sol_lua_check(sol::types<osd_file::error>, lua_State *L, int index, Handler &&handler, sol::stack::record &tracking)
{
	return sol::stack::check<int>(L, index, std::forward<Handler>(handler));
}

int sol_lua_push(sol::types<map_handler_type>, lua_State *L, map_handler_type &&value)
{
	const char *typestr;
	switch(value)
	{
		case AMH_NONE:
			typestr = "none";
			break;
		case AMH_RAM:
			typestr = "ram";
			break;
		case AMH_ROM:
			typestr = "rom";
			break;
		case AMH_NOP:
			typestr = "nop";
			break;
		case AMH_UNMAP:
			typestr = "unmap";
			break;
		case AMH_DEVICE_DELEGATE:
		case AMH_DEVICE_DELEGATE_M:
		case AMH_DEVICE_DELEGATE_S:
		case AMH_DEVICE_DELEGATE_SM:
		case AMH_DEVICE_DELEGATE_MO:
		case AMH_DEVICE_DELEGATE_SMO:
			typestr = "delegate";
			break;
		case AMH_PORT:
			typestr = "port";
			break;
		case AMH_BANK:
			typestr = "bank";
			break;
		case AMH_DEVICE_SUBMAP:
			typestr = "submap";
			break;
		default:
			typestr = "unknown";
			break;
	}
	return sol::stack::push(L, typestr);
}


//-------------------------------------------------
//  process_snapshot_filename - processes a snapshot
//  filename
//-------------------------------------------------

static std::string process_snapshot_filename(running_machine &machine, const char *s)
{
	std::string result(s);
	if (!osd_is_absolute_path(s))
	{
		strreplace(result, "/", PATH_SEPARATOR);
		strreplace(result, "%g", machine.basename());
	}
	return result;
}


//-------------------------------------------------
//  lua_engine - constructor
//-------------------------------------------------

lua_engine::lua_engine()
{
	m_machine = nullptr;
	m_lua_state = luaL_newstate();  /* create state */
	m_sol_state = std::make_unique<sol::state_view>(m_lua_state); // create sol view

	luaL_checkversion(m_lua_state);
	lua_gc(m_lua_state, LUA_GCSTOP, 0);  /* stop collector during initialization */
	sol().open_libraries();

	// Get package.preload so we can store builtins in it.
	sol()["package"]["preload"]["zlib"] = &luaopen_zlib;
	sol()["package"]["preload"]["lfs"] = &luaopen_lfs;
	sol()["package"]["preload"]["linenoise"] = &luaopen_linenoise;
	sol()["package"]["preload"]["lsqlite3"] = &luaopen_lsqlite3;

	lua_gc(m_lua_state, LUA_GCRESTART, 0);
}

//-------------------------------------------------
//  ~lua_engine - destructor
//-------------------------------------------------

lua_engine::~lua_engine()
{
	close();
}

sol::object lua_engine::call_plugin(const std::string &name, sol::object in)
{
	std::string field = "cb_" + name;
	sol::object obj = sol().registry()[field];
	if(obj.is<sol::protected_function>())
	{
		auto res = invoke(obj.as<sol::protected_function>(), in);
		if(!res.valid())
		{
			sol::error err = res;
			osd_printf_error("[LUA ERROR] in call_plugin: %s\n", err.what());
		}
		else
			return res.get<sol::object>();
	}
	return sol::make_object(sol(), sol::lua_nil);
}

void lua_engine::menu_populate(const std::string &menu, std::vector<std::tuple<std::string, std::string, std::string>> &menu_list)
{
	std::string field = "menu_pop_" + menu;
	sol::object obj = sol().registry()[field];
	if(obj.is<sol::protected_function>())
	{
		auto res = invoke(obj.as<sol::protected_function>());
		if(!res.valid())
		{
			sol::error err = res;
			osd_printf_error("[LUA ERROR] in menu_populate: %s\n", err.what());
		}
		else
		{
			sol::table table = res;
			for(auto &entry : table)
			{
				if(entry.second.is<sol::table>())
				{
					sol::table enttable = entry.second.as<sol::table>();
					menu_list.emplace_back(enttable.get<std::string, std::string, std::string>(1, 2, 3));
				}
			}
		}
	}
}

bool lua_engine::menu_callback(const std::string &menu, int index, const std::string &event)
{
	std::string field = "menu_cb_" + menu;
	bool ret = false;
	sol::object obj = sol().registry()[field];
	if(obj.is<sol::protected_function>())
	{
		auto res = invoke(obj.as<sol::protected_function>(), index, event);
		if(!res.valid())
		{
			sol::error err = res;
			osd_printf_error("[LUA ERROR] in menu_callback: %s\n", err.what());
		}
		else
			ret = res;
	}
	return ret;
}

void lua_engine::set_machine(running_machine *machine)
{
	if (!machine || (machine != m_machine))
		m_seq_poll.reset();
	m_machine = machine;
}

int lua_engine::enumerate_functions(const char *id, std::function<bool(const sol::protected_function &func)> &&callback)
{
	int count = 0;
	sol::object functable = sol().registry()[id];
	if (functable.is<sol::table>())
	{
		for (auto &func : functable.as<sol::table>())
		{
			if (func.second.is<sol::protected_function>())
			{
				bool cont = callback(func.second.as<sol::protected_function>());
				count++;
				if (!cont)
					break;
			}
		}
		return true;
	}
	return count;
}

bool lua_engine::execute_function(const char *id)
{
	int count = enumerate_functions(id, [this](const sol::protected_function &func)
	{
		auto ret = invoke(func);
		if(!ret.valid())
		{
			sol::error err = ret;
			osd_printf_error("[LUA ERROR] in execute_function: %s\n", err.what());
		}
		return true;
	});
	return count > 0;
}

void lua_engine::register_function(sol::function func, const char *id)
{
	sol::object functable = sol().registry()[id];
	if(functable.is<sol::table>())
		functable.as<sol::table>().add(func);
	else
		sol().registry().create_named(id, 1, func);
}

void lua_engine::on_machine_prestart()
{
	execute_function("LUA_ON_PRESTART");
}

void lua_engine::on_machine_start()
{
	execute_function("LUA_ON_START");
}

void lua_engine::on_machine_stop()
{
	execute_function("LUA_ON_STOP");
}

void lua_engine::on_machine_before_load_settings()
{
	execute_function("LUA_ON_BEFORE_LOAD_SETTINGS");
}

void lua_engine::on_machine_pause()
{
	execute_function("LUA_ON_PAUSE");
}

void lua_engine::on_machine_resume()
{
	execute_function("LUA_ON_RESUME");
}

void lua_engine::on_machine_frame()
{
	execute_function("LUA_ON_FRAME");
}

void lua_engine::on_frame_done()
{
	execute_function("LUA_ON_FRAME_DONE");
}

void lua_engine::on_sound_update()
{
	execute_function("LUA_ON_SOUND_UPDATE");
}

void lua_engine::on_periodic()
{
	execute_function("LUA_ON_PERIODIC");
}

bool lua_engine::on_missing_mandatory_image(const std::string &instance_name)
{
	bool handled = false;
	enumerate_functions("LUA_ON_MANDATORY_FILE_MANAGER_OVERRIDE", [this, &instance_name, &handled](const sol::protected_function &func)
	{
		auto ret = invoke(func, instance_name);

		if(!ret.valid())
		{
			sol::error err = ret;
			osd_printf_error("[LUA ERROR] in on_missing_mandatory_image: %s\n", err.what());
		}
		else if (ret.get<bool>())
		{
			handled = true;
		}
		return !handled;
	});
	return handled;
}

void lua_engine::attach_notifiers()
{
	machine().add_notifier(MACHINE_NOTIFY_RESET, machine_notify_delegate(&lua_engine::on_machine_prestart, this), true);
	machine().add_notifier(MACHINE_NOTIFY_RESET, machine_notify_delegate(&lua_engine::on_machine_start, this));
	machine().add_notifier(MACHINE_NOTIFY_EXIT, machine_notify_delegate(&lua_engine::on_machine_stop, this));
	machine().add_notifier(MACHINE_NOTIFY_PAUSE, machine_notify_delegate(&lua_engine::on_machine_pause, this));
	machine().add_notifier(MACHINE_NOTIFY_RESUME, machine_notify_delegate(&lua_engine::on_machine_resume, this));
	machine().add_notifier(MACHINE_NOTIFY_FRAME, machine_notify_delegate(&lua_engine::on_machine_frame, this));
}

//-------------------------------------------------
//  initialize - initialize lua hookup to emu engine
//-------------------------------------------------

void lua_engine::initialize()
{

	static const enum_parser<movie_recording::format, 2> s_movie_recording_format_parser =
	{
		{ "avi", movie_recording::format::AVI },
		{ "mng", movie_recording::format::MNG }
	};


	static const enum_parser<ui::text_layout::text_justify, 3> s_text_justify_parser =
	{
		{ "left", ui::text_layout::LEFT },
		{ "right", ui::text_layout::RIGHT },
		{ "center", ui::text_layout::CENTER },
	};


	static const enum_parser<int, 3> s_seek_parser =
	{
		{ "set", SEEK_SET },
		{ "cur", SEEK_CUR },
		{ "end", SEEK_END }
	};

/*  emu library
 *
 * emu.app_name() - return application name
 * emu.app_version() - return application version
 * emu.gamename() - return game full name
 * emu.romname() - return game ROM name
 * emu.softname() - return softlist name
 * emu.time() - return emulation time
 * emu.pid() - return frontend process ID
 *
 * emu.driver_find(driver_name) - find and return game_driver for driver_name
 * emu.start(driver_name) - start given driver_name
 * emu.pause() - pause emulation
 * emu.unpause() - unpause emulation
 * emu.step() - advance one frame
 * emu.keypost(keys) - post keys to natural keyboard
 * emu.wait(len) - wait for len within coroutine
 * emu.lang_translate(str) - get translation for str if available
 * emu.subst_env(str) - substitute environment variables with values for str
 *
 * emu.register_prestart(callback) - register callback before reset
 * emu.register_start(callback) - register callback after reset
 * emu.register_stop(callback) - register callback after stopping
 * emu.register_pause(callback) - register callback at pause
 * emu.register_resume(callback) - register callback at resume
 * emu.register_frame(callback) - register callback at end of frame
 * emu.register_frame_done(callback) - register callback after frame is drawn to screen (for overlays)
 * emu.register_sound_update(callback) - register callback after sound update has generated new samples
 * emu.register_periodic(callback) - register periodic callback while program is running
 * emu.register_callback(callback, name) - register callback to be used by MAME via lua_engine::call_plugin()
 * emu.register_menu(event_callback, populate_callback, name) - register callbacks for plugin menu
 * emu.register_mandatory_file_manager_override(callback) - register callback invoked to override mandatory file manager
 * emu.register_before_load_settings(callback) - register callback to be run before settings are loaded
 * emu.show_menu(menu_name) - show menu by name and pause the machine
 *
 * emu.print_verbose(str) - output to stderr at verbose level
 * emu.print_error(str) - output to stderr at error level
 * emu.print_info(str) - output to stderr at info level
 * emu.print_debug(str) - output to stderr at debug level
 *
 * emu.device_enumerator(dev) - get device enumerator starting at arbitrary point in tree
 * emu.screen_enumerator(dev) - get screen device enumerator starting at arbitrary point in tree
 * emu.image_enumerator(dev) - get image interface enumerator starting at arbitrary point in tree
 */

	sol::table emu = sol().create_named_table("emu");
	emu["app_name"] = &emulator_info::get_appname_lower;
	emu["app_version"] = &emulator_info::get_bare_build_version;
	emu["gamename"] = [this] () { return machine().system().type.fullname(); };
	emu["romname"] = [this] () { return machine().basename(); };
	emu["softname"] = [this] () { return machine().options().software_name(); };
	emu["keypost"] = [this] (const char *keys) { machine().ioport().natkeyboard().post_utf8(keys); };
	emu["time"] = [this] () { return machine().time().as_double(); };
	emu["start"] =
		[this](const char *driver)
		{
			int i = driver_list::find(driver);
			if (i != -1)
			{
				mame_machine_manager::instance()->schedule_new_driver(driver_list::driver(i));
				machine().schedule_hard_reset();
			}
			return 1;
		};
	emu["pause"] = [this] () { return machine().pause(); };
	emu["unpause"] = [this] () { return machine().resume(); };
	emu["step"] =
		[this] ()
		{
			mame_machine_manager::instance()->ui().set_single_step(true);
			machine().resume();
		};
	emu["register_prestart"] = [this] (sol::function func) { register_function(func, "LUA_ON_PRESTART"); };
	emu["register_start"] = [this] (sol::function func) { register_function(func, "LUA_ON_START"); };
	emu["register_stop"] = [this] (sol::function func) { register_function(func, "LUA_ON_STOP"); };
	emu["register_pause"] = [this] (sol::function func) { register_function(func, "LUA_ON_PAUSE"); };
	emu["register_resume"] = [this] (sol::function func) { register_function(func, "LUA_ON_RESUME"); };
	emu["register_frame"] = [this] (sol::function func) { register_function(func, "LUA_ON_FRAME"); };
	emu["register_frame_done"] = [this] (sol::function func) { register_function(func, "LUA_ON_FRAME_DONE"); };
	emu["register_sound_update"] = [this] (sol::function func) { register_function(func, "LUA_ON_SOUND_UPDATE"); };
	emu["register_periodic"] = [this] (sol::function func) { register_function(func, "LUA_ON_PERIODIC"); };
	emu["register_mandatory_file_manager_override"] = [this] (sol::function func) { register_function(func, "LUA_ON_MANDATORY_FILE_MANAGER_OVERRIDE"); };
	emu["register_before_load_settings"] = [this](sol::function func) { register_function(func, "LUA_ON_BEFORE_LOAD_SETTINGS"); };
	emu["register_menu"] =
		[this] (sol::function cb, sol::function pop, const std::string &name)
		{
			std::string cbfield = "menu_cb_" + name;
			std::string popfield = "menu_pop_" + name;
			sol().registry()[cbfield] = cb;
			sol().registry()[popfield] = pop;
			m_menu.push_back(name);
		};
	emu["show_menu"] =
		[this](const char *name)
		{
			mame_ui_manager &mui = mame_machine_manager::instance()->ui();
			render_container &container = machine().render().ui_container();
			ui::menu_plugin::show_menu(mui, container, (char *)name);
		};
	emu["register_callback"] =
		[this] (sol::function cb, const std::string &name)
		{
			std::string field = "cb_" + name;
			sol().registry()[field] = cb;
		};
	emu["print_verbose"] = [] (const char *str) { osd_printf_verbose("%s\n", str); };
	emu["print_error"] = [] (const char *str) { osd_printf_error("%s\n", str); };
	emu["print_info"] = [] (const char *str) { osd_printf_info("%s\n", str); };
	emu["print_debug"] = [] (const char *str) { osd_printf_debug("%s\n", str); };
	emu["driver_find"] =
		[this] (const char *driver) -> sol::object
		{
			const int i = driver_list::find(driver);
			if (i < 0)
				return sol::make_object(sol(), sol::lua_nil);
			return sol::make_object(sol(), driver_list::driver(i));
		};
	emu["wait"] = lua_CFunction(
			[](lua_State *L)
			{
				lua_engine *engine = mame_machine_manager::instance()->lua();
				luaL_argcheck(L, lua_isnumber(L, 1), 1, "waiting duration expected");
				int ret = lua_pushthread(L);
				if (ret == 1)
					return luaL_error(L, "cannot wait from outside coroutine");
				int ref = luaL_ref(L, LUA_REGISTRYINDEX);
				engine->machine().scheduler().timer_set(attotime::from_double(lua_tonumber(L, 1)), timer_expired_delegate(FUNC(lua_engine::resume), engine), ref, nullptr);
				return lua_yield(L, 0);
			});
	emu["lang_translate"] = &lang_translate;
	emu["pid"] = &osd_getpid;
	emu["subst_env"] =
		[] (const std::string &str)
		{
			std::string result;
			osd_subst_env(result, str);
			return result;
		};
	emu["device_enumerator"] = [] (device_t &d) { return devenum<device_enumerator>(d); };
	emu["screen_enumerator"] = [] (device_t &d) { return devenum<screen_device_enumerator>(d); };
	emu["image_enumerator"] = [] (device_t &d) { return devenum<image_interface_enumerator>(d); };


/* emu_file library
 *
 * emu.file([opt] searchpath, flags) - flags can be as in osdcore "OPEN_FLAG_*" or lua style
 *                                     with 'rwc' with addtional c for create *and truncate*
 *                                     (be careful) support zipped files on the searchpath
 *
 * file:open(name) - open first file matching name in searchpath. supports read
 *                   and write sockets as "socket.127.0.0.1:1234"
 * file:open_next() - open next file matching name in searchpath
 * file:read(len) - only reads len bytes, doesn't do lua style formats
 * file:write(data) - write data to file
 * file:seek(offset, whence) - whence is as C "SEEK_*" int
 * file:seek([opt] whence, [opt] offset) - lua style "set"|"cur"|"end", returns cur offset
 * file:size() - file size in bytes
 * file:filename() - name of current file, container name if file is in zip
 * file:fullpath() -
*/

	auto file_type = emu.new_usertype<emu_file>("file", sol::call_constructor, sol::initializers(
				[](emu_file &file, u32 flags) { new (&file) emu_file(flags); },
				[](emu_file &file, const char *path, u32 flags) { new (&file) emu_file(path, flags); },
				[](emu_file &file, const char *mode) {
					int flags = 0;
					for(int i = 0; i < 3 && mode[i]; i++) // limit to three chars
					{
						switch(mode[i])
						{
							case 'r':
								flags |= OPEN_FLAG_READ;
								break;
							case 'w':
								flags |= OPEN_FLAG_WRITE;
								break;
							case 'c':
								flags |= OPEN_FLAG_CREATE;
								break;
						}
					}
					new (&file) emu_file(flags);
				},
				[](emu_file &file, const char *path, const char* mode) {
					int flags = 0;
					for(int i = 0; i < 3 && mode[i]; i++) // limit to three chars
					{
						switch(mode[i])
						{
							case 'r':
								flags |= OPEN_FLAG_READ;
								break;
							case 'w':
								flags |= OPEN_FLAG_WRITE;
								break;
							case 'c':
								flags |= OPEN_FLAG_CREATE;
								break;
						}
					}
					new (&file) emu_file(path, flags);
				}));
	file_type.set("read", [](emu_file &file, sol::buffer *buff) { buff->set_len(file.read(buff->get_ptr(), buff->get_len())); return buff; });
	file_type.set("write", [](emu_file &file, const std::string &data) { return file.write(data.data(), data.size()); });
	file_type.set("open", static_cast<osd_file::error (emu_file::*)(const std::string &)>(&emu_file::open));
	file_type.set("open_next", &emu_file::open_next);
	file_type.set("seek", sol::overload(
			[](emu_file &file) { return file.tell(); },
			[this](emu_file &file, s64 offset, int whence) -> sol::object {
				if(file.seek(offset, whence))
					return sol::make_object(sol(), sol::lua_nil);
				else
					return sol::make_object(sol(), file.tell());
			},
			[this](emu_file &file, const char* whence) -> sol::object {
				int wval = s_seek_parser(whence);
				if(wval < 0 || wval >= 3)
					return sol::make_object(sol(), sol::lua_nil);
				if(file.seek(0, wval))
					return sol::make_object(sol(), sol::lua_nil);
				return sol::make_object(sol(), file.tell());
			},
			[this](emu_file &file, const char* whence, s64 offset) -> sol::object {
				int wval = s_seek_parser(whence);
				if(wval < 0 || wval >= 3)
					return sol::make_object(sol(), sol::lua_nil);
				if(file.seek(offset, wval))
					return sol::make_object(sol(), sol::lua_nil);
				return sol::make_object(sol(), file.tell());
			}));
	file_type.set("size", &emu_file::size);
	file_type.set("filename", &emu_file::filename);
	file_type.set("fullpath", &emu_file::fullpath);


/*  thread library
 *
 * emu.thread()
 *
 * thread:start(scr) - run scr (lua code as string) in a separate thread
 *                     in a new empty (other than modules) lua context.
 *                     thread runs until yield() and/or terminates on return.
 * thread:continue(val) - resume thread that has yielded and pass val to it
 *
 * thread.result - get result of a terminated thread as string
 * thread.busy - check if thread is running
 * thread.yield - check if thread is yielded
 */

	auto thread_type = emu.new_usertype<context>("thread", sol::call_constructor, sol::constructors<sol::types<>>());
	thread_type.set("start", [](context &ctx, const char *scr) {
			std::string script(scr);
			if(ctx.busy)
				return false;
			std::thread th([&ctx, script]() {
					sol::state thstate;
					thstate.open_libraries();
					thstate["package"]["preload"]["zlib"] = &luaopen_zlib;
					thstate["package"]["preload"]["lfs"] = &luaopen_lfs;
					thstate["package"]["preload"]["linenoise"] = &luaopen_linenoise;
					sol::load_result res = thstate.load(script);
					if(res.valid())
					{
						sol::protected_function func = res.get<sol::protected_function>();
						thstate["yield"] = [&ctx, &thstate]() {
								std::mutex m;
								std::unique_lock<std::mutex> lock(m);
								ctx.result = thstate["status"];
								ctx.yield = true;
								ctx.sync.wait(lock);
								ctx.yield = false;
								thstate["status"] = ctx.result;
							};
						auto ret = func();
						if (ret.valid()) {
							const char *tmp = ret.get<const char *>();
							if (tmp != nullptr)
								ctx.result = tmp;
							else
								exit(0);
						}
					}
					ctx.busy = false;
				});
			ctx.busy = true;
			ctx.yield = false;
			th.detach();
			return true;
		});
	thread_type.set("continue", [](context &ctx, const char *val) {
			if(!ctx.yield)
				return;
			ctx.result = val;
			ctx.sync.notify_all();
		});
	thread_type.set("result", sol::property([](context &ctx) -> std::string {
			if(ctx.busy && !ctx.yield)
				return "";
			return ctx.result;
		}));
	thread_type.set("busy", sol::readonly(&context::busy));
	thread_type.set("yield", sol::readonly(&context::yield));


/*  save_item library
 *
 * emu.item(item_index)
 *
 * item.size - size of the raw data type
 * item.count - number of entries
 *
 * item:read(offset) - read entry value by index
 * item:read_block(offset, count) - read a block of entry values as a string (byte addressing)
 * item:write(offset, value) - write entry value by index
 */

	auto item_type = emu.new_usertype<save_item>("item", sol::call_constructor, sol::initializers([this](save_item &item, int index) {
					if(machine().save().indexed_item(index, item.base, item.size, item.valcount, item.blockcount, item.stride))
					{
						item.count = item.valcount * item.blockcount;
					}
					else
					{
						item.base = nullptr;
						item.size = 0;
						item.count = 0;
						item.valcount = 0;
						item.blockcount = 0;
						item.stride = 0;
					}
				}));
	item_type.set("size", sol::readonly(&save_item::size));
	item_type.set("count", sol::readonly(&save_item::count));
	item_type.set("read", [this](save_item &item, int offset) -> sol::object {
			if(!item.base || (offset >= item.count))
				return sol::make_object(sol(), sol::lua_nil);
			const void *const data = reinterpret_cast<const uint8_t *>(item.base) + (item.stride * (offset / item.valcount));
			uint64_t ret = 0;
			switch(item.size)
			{
				case 1:
				default:
					ret = reinterpret_cast<const uint8_t *>(data)[offset % item.valcount];
					break;
				case 2:
					ret = reinterpret_cast<const uint16_t *>(data)[offset % item.valcount];
					break;
				case 4:
					ret = reinterpret_cast<const uint32_t *>(data)[offset % item.valcount];
					break;
				case 8:
					ret = reinterpret_cast<const uint64_t *>(data)[offset % item.valcount];
					break;
			}
			return sol::make_object(sol(), ret);
		});
	item_type.set("read_block", [](save_item &item, int offset, sol::buffer *buff) {
			if(!item.base || ((offset + buff->get_len()) > (item.size * item.count)))
			{
				buff->set_len(0);
			}
			else
			{
				const uint32_t blocksize = item.size * item.valcount;
				uint32_t remaining = buff->get_len();
				uint8_t *dest = reinterpret_cast<uint8_t *>(buff->get_ptr());
				while(remaining)
				{
					const uint32_t blockno = offset / blocksize;
					const uint32_t available = blocksize - (offset % blocksize);
					const uint32_t chunk = (available < remaining) ? available : remaining;
					const void *const source = reinterpret_cast<const uint8_t *>(item.base) + (blockno * item.stride) + (offset % blocksize);
					std::memcpy(dest, source, chunk);
					offset += chunk;
					remaining -= chunk;
					dest += chunk;
				}
			}
			return buff;
		});
	item_type.set("write", [](save_item &item, int offset, uint64_t value) {
			if(!item.base || (offset >= item.count))
				return;
			void *const data = reinterpret_cast<uint8_t *>(item.base) + (item.stride * (offset / item.valcount));
			switch(item.size)
			{
				case 1:
				default:
					reinterpret_cast<uint8_t *>(data)[offset % item.valcount] = uint8_t(value);
					break;
				case 2:
					reinterpret_cast<uint16_t *>(data)[offset % item.valcount] = uint16_t(value);
					break;
				case 4:
					reinterpret_cast<uint32_t *>(data)[offset % item.valcount] = uint32_t(value);
					break;
				case 8:
					reinterpret_cast<uint64_t *>(data)[offset % item.valcount] = uint64_t(value);
					break;
			}
		});


/* core_options library
 *
 * manager:options()
 * manager:machine():options()
 * manager:ui():options()
 * manager:plugins()
 *
 * options:help() - get help for options
 * options:command(command) - return output for command
 *
 * options.entries[] - get table of option entries (k=name, v=core_options::entry)
 */

	auto core_options_type = sol().registry().new_usertype<core_options>("core_options", "new", sol::no_constructor);
	core_options_type.set("help", &core_options::output_help);
	core_options_type.set("command", &core_options::command);
	core_options_type.set("entries", sol::property([this](core_options &options) {
			sol::table table = sol().create_table();
			int unadorned_index = 0;
			for (auto &curentry : options.entries())
			{
				const char *name = curentry->names().size() > 0
					? curentry->name().c_str()
					: nullptr;
				bool is_unadorned = false;
				// check if it's unadorned
				if (name && strlen(name) && !strcmp(name, options.unadorned(unadorned_index)))
				{
					unadorned_index++;
					is_unadorned = true;
				}
				if (curentry->type() != core_options::option_type::HEADER && curentry->type() != core_options::option_type::COMMAND && !is_unadorned)
					table[name] = &*curentry;
			}
			return table;
		}));

/*  emu_options library
 *
 * manager:options()
 * manager:machine():options()
 *
 * options:slot_option() - retrieves a specific slot option
 */

	auto emu_options_type = sol().registry().new_usertype<emu_options>("emu_options", sol::no_constructor, sol::base_classes, sol::bases<core_options>());
	emu_options_type.set("slot_option", [](emu_options &opts, const std::string &name) { return opts.find_slot_option(name); });


/*  slot_option library
 *
 * manager:options():slot_option("name")
 * manager:machine():options():slot_option("name")
 *
 * slot_option.value - the actual value of the option, after being interpreted
 * slot_option.specified_value - the value of the option, as specified from outside
 * slot_option.bios - the bios, if any, associated with the slot
 * slot_option.default_card_software - the software list item that is associated with this option, by default
 * slot_option:specify() - specifies the value of the slot, potentially causing a recalculation
 */

	auto slot_option_type = sol().registry().new_usertype<slot_option>("slot_option", sol::no_constructor);
	slot_option_type["value"] = sol::property(&slot_option::value);
	slot_option_type["specified_value"] = sol::property(&slot_option::specified_value);
	slot_option_type["bios"] = sol::property(&slot_option::bios);
	slot_option_type["default_card_software"] = sol::property(&slot_option::default_card_software);
	slot_option_type.set("specify", [](slot_option &opt, std::string &&text, const char *bios) {
			opt.specify(std::move(text));
			if (bios)
				opt.set_bios(bios);
		});


/*  core_options::entry library
 *
 * options.entries[entry_name]
 *
 * entry:value() - get value of entry
 * entry:value(val) - set entry to val
 * entry:description() - get info about entry
 * entry:default_value() - get default for entry
 * entry:minimum() - get min value for entry
 * entry:maximum() - get max value for entry
 * entry:has_range() - are min and max valid for entry
 */

	auto core_options_entry_type = sol().registry().new_usertype<core_options::entry>("core_options_entry", "new", sol::no_constructor);
	core_options_entry_type.set("value", sol::overload(
		[this](core_options::entry &e, bool val) {
			if(e.type() != OPTION_BOOLEAN)
				luaL_error(m_lua_state, "Cannot set option to wrong type");
			else
				e.set_value(val ? "1" : "0", OPTION_PRIORITY_CMDLINE);
		},
		[this](core_options::entry &e, float val) {
			if(e.type() != OPTION_FLOAT)
				luaL_error(m_lua_state, "Cannot set option to wrong type");
			else
				e.set_value(string_format("%f", val), OPTION_PRIORITY_CMDLINE);
		},
		[this](core_options::entry &e, int val) {
			if(e.type() != OPTION_INTEGER)
				luaL_error(m_lua_state, "Cannot set option to wrong type");
			else
				e.set_value(string_format("%d", val), OPTION_PRIORITY_CMDLINE);
		},
		[this](core_options::entry &e, const char *val) {
			if(e.type() != OPTION_STRING)
				luaL_error(m_lua_state, "Cannot set option to wrong type");
			else
				e.set_value(val, OPTION_PRIORITY_CMDLINE);
		},
		[this](core_options::entry &e) -> sol::object {
			if (e.type() == core_options::option_type::INVALID)
				return sol::make_object(sol(), sol::lua_nil);
			switch(e.type())
			{
				case core_options::option_type::BOOLEAN:
					return sol::make_object(sol(), atoi(e.value()) != 0);
				case core_options::option_type::INTEGER:
					return sol::make_object(sol(), atoi(e.value()));
				case core_options::option_type::FLOAT:
					return sol::make_object(sol(), atof(e.value()));
				default:
					return sol::make_object(sol(), e.value());
			}
		}));
	core_options_entry_type.set("description", &core_options::entry::description);
	core_options_entry_type.set("default_value", &core_options::entry::default_value);
	core_options_entry_type.set("minimum", &core_options::entry::minimum);
	core_options_entry_type.set("maximum", &core_options::entry::maximum);
	core_options_entry_type.set("has_range", &core_options::entry::has_range);


/*  running_machine library
 *
 * manager:machine()
 *
 * machine:exit() - close program
 * machine:hard_reset() - hard reset emulation
 * machine:soft_reset() - soft reset emulation
 * machine:save(filename) - save state to filename
 * machine:load(filename) - load state from filename
 * machine:buffer_save() - return save state buffer as binary string
 * machine:buffer_load(str) - load state from binary string buffer. returns true on success, otherwise nil
 * machine:popmessage(str) - print str as popup
 * machine:popmessage() - clear displayed popup message
 * machine:logerror(str) - print str to log
 * machine:system() - get game_driver for running driver
 * machine:video() - get video_manager
 * machine:sound() - get sound_manager
 * machine:render() - get render_manager
 * machine:ioport() - get ioport_manager
 * machine:parameters() - get parameter_manager
 * machine:memory() - get memory_manager
 * machine:options() - get machine emu_options
 * machine:outputs() - get output_manager
 * machine:input() - get input_manager
 * machine:uiinput() - get ui_input_manager
 * machine:debugger() - get debugger_manager
 *
 * machine.paused - get paused state
 * machine.samplerate - get audio sample rate
 * machine.exit_pending
 * machine.hard_reset_pending
 *
 * machine.devices[] - get device table (k=tag, v=device_t)
 * machine.screens[] - get screens table (k=tag, v=screen_device)
 * machine.images[] - get available image devices table (k=type, v=device_image_interface)
 */

	auto machine_type = sol().registry().new_usertype<running_machine>("machine", "new", sol::no_constructor);
	machine_type["exit"] = &running_machine::schedule_exit;
	machine_type["hard_reset"] = &running_machine::schedule_hard_reset;
	machine_type["soft_reset"] = &running_machine::schedule_soft_reset;
	machine_type["save"] = &running_machine::schedule_save;
	machine_type["load"] = &running_machine::schedule_load;
	machine_type["buffer_save"] =
		[] (running_machine &m, sol::this_state s)
		{
			lua_State *L = s;
			luaL_Buffer buff;
			int size = ram_state::get_size(m.save());
			u8 *ptr = (u8 *)luaL_buffinitsize(L, &buff, size);
			save_error error = m.save().write_buffer(ptr, size);
			if (error == STATERR_NONE)
			{
				luaL_pushresultsize(&buff, size);
				return sol::make_reference(L, sol::stack_reference(L, -1));
			}
			luaL_error(L, "State save error.");
			return sol::make_reference(L, nullptr);
		};
	machine_type["buffer_load"] =
		[] (running_machine &m, sol::this_state s, std::string str)
		{
			lua_State *L = s;
			save_error error = m.save().read_buffer((u8 *)str.data(), str.size());
			if (error == STATERR_NONE)
				return true;
			else
			{
				luaL_error(L,"State load error.");
				return false;
			}
		};
	machine_type["system"] = &running_machine::system;
	machine_type["video"] = &running_machine::video;
	machine_type["sound"] = &running_machine::sound;
	machine_type["render"] = &running_machine::render;
	machine_type["ioport"] = &running_machine::ioport;
	machine_type["parameters"] = &running_machine::parameters;
	machine_type["memory"] = &running_machine::memory;
	machine_type["options"] = &running_machine::options;
	machine_type["outputs"] = &running_machine::output;
	machine_type["input"] = &running_machine::input;
	machine_type["uiinput"] = &running_machine::ui_input;
	machine_type["debugger"] =
		[this] (running_machine &m) -> sol::object
		{
			if(!(m.debug_flags & DEBUG_FLAG_ENABLED))
				return sol::make_object(sol(), sol::lua_nil);
			return sol::make_object(sol(), &m.debugger());
		};
	machine_type["paused"] = sol::property(&running_machine::paused);
	machine_type["samplerate"] = sol::property(&running_machine::sample_rate);
	machine_type["exit_pending"] = sol::property(&running_machine::exit_pending);
	machine_type["hard_reset_pending"] = sol::property(&running_machine::hard_reset_pending);
	machine_type["devices"] = sol::property([] (running_machine &m) { return devenum<device_enumerator>(m.root_device()); });
	machine_type["screens"] = sol::property([] (running_machine &m) { return devenum<screen_device_enumerator>(m.root_device()); });
	machine_type["cassettes"] = sol::property([] (running_machine &m) { return devenum<cassette_device_enumerator>(m.root_device()); });
	machine_type["images"] = sol::property([] (running_machine &m) { return devenum<image_interface_enumerator>(m.root_device()); });
	machine_type["slots"] = sol::property([](running_machine &m) { return devenum<slot_interface_enumerator>(m.root_device()); });
	machine_type["popmessage"] = sol::overload(
			[](running_machine &m, const char *str) { m.popmessage("%s", str); },
			[](running_machine &m) { m.popmessage(); });
	machine_type["logerror"]  = [] (running_machine &m, const char *str) { m.logerror("[luaengine] %s\n", str); };


/* game_driver library
 *
 * emu.driver_find(driver_name)
 *
 * driver.source_file - relative path to the source file
 * driver.parent
 * driver.name
 * driver.description
 * driver.year
 * driver.manufacturer
 * driver.compatible_with
 * driver.default_layout
 * driver.orientation - screen rotation degree (rot0/90/180/270)
 * driver.type - machine type (arcade/console/computer/other)
 * driver.not_working - not considered working
 * driver.supports_save - supports save states
 * driver.no_cocktail - screen flip support is missing
 * driver.is_bios_root - this driver entry is a BIOS root
 * driver.requires_artwork - requires external artwork for key game elements
 * driver.clickable_artwork - artwork is clickable and requires mouse cursor
 * driver.unofficial - unofficial hardware modification
 * driver.no_sound_hw - system has no sound output
 * driver.mechanical - contains mechanical parts (pinball, redemption games, ...)
 * driver.is_incomplete - official system with blatantly incomplete hardware/software
 */

	auto game_driver_type = sol().registry().new_usertype<game_driver>("game_driver", sol::no_constructor);
	game_driver_type["source_file"] = sol::property([] (game_driver const &driver) { return &driver.type.source()[0]; });
	game_driver_type["parent"] = sol::readonly(&game_driver::parent);
	game_driver_type["name"] = sol::property([] (game_driver const &driver) { return &driver.name[0]; });
	game_driver_type["description"] = sol::property([] (game_driver const &driver) { return &driver.type.fullname()[0]; });
	game_driver_type["year"] = sol::readonly(&game_driver::year);
	game_driver_type["manufacturer"] = sol::readonly(&game_driver::manufacturer);
	game_driver_type["compatible_with"] = sol::readonly(&game_driver::compatible_with);
	game_driver_type["default_layout"] = sol::readonly(&game_driver::default_layout);
	game_driver_type["orientation"] = sol::property(
			[] (game_driver const &driver)
			{
				std::string rot;
				switch (driver.flags & machine_flags::MASK_ORIENTATION)
				{
				case machine_flags::ROT0:
					rot = "rot0";
					break;
				case machine_flags::ROT90:
					rot = "rot90";
					break;
				case machine_flags::ROT180:
					rot = "rot180";
					break;
				case machine_flags::ROT270:
					rot = "rot270";
					break;
				default:
					rot = "undefined";
					break;
				}
				return rot;
			});
	game_driver_type["type"] = sol::property(
			[](game_driver const &driver)
			{
				std::string type;
				switch (driver.flags & machine_flags::MASK_TYPE)
				{
				case machine_flags::TYPE_ARCADE:
					type = "arcade";
					break;
				case machine_flags::TYPE_CONSOLE:
					type = "console";
					break;
				case machine_flags::TYPE_COMPUTER:
					type = "computer";
					break;
				default:
					type = "other";
					break;
				}
				return type;
			});
	game_driver_type["not_working"] = sol::property([] (game_driver const &driver) { return (driver.flags & machine_flags::NOT_WORKING) != 0; });
	game_driver_type["supports_save"] = sol::property([] (game_driver const &driver) { return (driver.flags & machine_flags::SUPPORTS_SAVE) != 0; });
	game_driver_type["no_cocktail"] = sol::property([] (game_driver const &driver) { return (driver.flags & machine_flags::NO_COCKTAIL) != 0; });
	game_driver_type["is_bios_root"] = sol::property([] (game_driver const &driver) { return (driver.flags & machine_flags::IS_BIOS_ROOT) != 0; });
	game_driver_type["requires_artwork"] = sol::property([] (game_driver const &driver) { return (driver.flags & machine_flags::REQUIRES_ARTWORK) != 0; });
	game_driver_type["clickable_artwork"] = sol::property([] (game_driver const &driver) { return (driver.flags & machine_flags::CLICKABLE_ARTWORK) != 0; });
	game_driver_type["unofficial"] = sol::property([] (game_driver const &driver) { return (driver.flags & machine_flags::UNOFFICIAL) != 0; });
	game_driver_type["no_sound_hw"] = sol::property([] (game_driver const &driver) { return (driver.flags & machine_flags::NO_SOUND_HW) != 0; });
	game_driver_type["mechanical"] = sol::property([] (game_driver const &driver) { return (driver.flags & machine_flags::MECHANICAL) != 0; });
	game_driver_type["is_incomplete"] = sol::property([] (game_driver const &driver) { return (driver.flags & machine_flags::IS_INCOMPLETE) != 0; });


/* device_t library
 *
 * manager:machine().devices[device_tag]
 *
 * device:subtag(tag) - get absolute tag relative to this device
 * device:siblingtag(tag) - get absolute tag relative to this device
 * device:memregion(tag) - get memory region
 * device:memshare(tag) - get memory share
 * device:membank(tag) - get memory bank
 * device:subdevice(tag) - get subdevice
 * device:siblingdevice(tag) - get sibling device
 * device:debug() - debug interface, CPUs only
 *
 * device.tag - device tree tag
 * device.basetag - last component of tag ("root" for root device)
 * device.name - device type full name
 * device.shortname - device type short name
 * device.owner - parent device (nil for root device)
 * device.configured - whether configuration is complete
 * device.started - whether the device has been started
 * device.spaces[] - device address spaces table (k=name, v=addr_space)
 * device.state[] - device state entries table (k=name, v=device_state_entry)
 * device.items[] - device save state items table (k=name, v=index)
 * device.roms[] - device rom entry table (k=name, v=rom_entry)
 */

	auto device_type = sol().registry().new_usertype<device_t>("device", sol::no_constructor);
	device_type["subtag"] = &device_t::subtag;
	device_type["siblingtag"] = &device_t::siblingtag;
	device_type["memregion"] = &device_t::memregion;
	device_type["memshare"] = &device_t::memshare;
	device_type["membank"] = &device_t::membank;
	device_type["subdevice"] = static_cast<device_t *(device_t::*)(char const *) const>(&device_t::subdevice);
	device_type["siblingdevice"] = static_cast<device_t *(device_t::*)(char const *) const>(&device_t::siblingdevice);
	device_type["debug"] =
		[this] (device_t &dev) -> sol::object
		{
			if (!(dev.machine().debug_flags & DEBUG_FLAG_ENABLED) || !dynamic_cast<cpu_device *>(&dev)) // debugger not enabled or not cpu
				return sol::make_object(sol(), sol::lua_nil);
			return sol::make_object(sol(), dev.debug());
		};
	device_type["tag"] = sol::property(&device_t::tag);
	device_type["basetag"] = sol::property(&device_t::basetag);
	device_type["name"] = sol::property(&device_t::name);
	device_type["shortname"] = sol::property(&device_t::shortname);
	device_type["owner"] = sol::property(&device_t::owner);
	device_type["configured"] = sol::property(&device_t::configured);
	device_type["started"] = sol::property(&device_t::started);
	device_type["spaces"] = sol::property(
			[this] (device_t &dev)
			{
				device_memory_interface *memdev = dynamic_cast<device_memory_interface *>(&dev);
				sol::table sp_table = sol().create_table();
				if(!memdev)
					return sp_table;
				for(int sp = 0; sp < memdev->max_space_count(); ++sp)
				{
					if(memdev->has_space(sp))
						sp_table[memdev->space(sp).name()] = addr_space(memdev->space(sp), *memdev);
				}
				return sp_table;
			});
	device_type["state"] = sol::property(
			[this] (device_t &dev)
			{
				sol::table st_table = sol().create_table();
				if(!dynamic_cast<device_state_interface *>(&dev))
					return st_table;
				// XXX: refrain from exporting non-visible entries?
				for(auto &s : dev.state().state_entries())
					st_table[s->symbol()] = s.get();
				return st_table;
			});
	device_type["items"] = sol::property(
			[this] (device_t &dev)
			{
				sol::table table = sol().create_table();
				std::string tag = dev.tag();
				// 10000 is enough?
				for(int i = 0; i < 10000; i++)
				{
					std::string name;
					const char *item;
					void *base;
					uint32_t size, valcount, blockcount, stride;
					item = dev.machine().save().indexed_item(i, base, size, valcount, blockcount, stride);
					if(!item)
						break;
					name = &(strchr(item, '/')[1]);
					if(name.substr(0, name.find('/')) == tag)
					{
						name = name.substr(name.find('/') + 1, std::string::npos);
						table[name] = i;
					}
				}
				return table;
			});
	device_type["roms"] = sol::property(
			[this] (device_t &dev)
			{
				sol::table table = sol().create_table();
				for(auto rom : dev.rom_region_vector())
					if(!rom.name().empty())
						table[rom.name()] = rom;
				return table;
			});


/*  parameters_manager library
 *
 * manager:machine():parameters()
 *
 * parameters:add(tag, val) - add tag = val parameter
 * parameters:lookup(tag) - get val for tag
 */

	auto parameters_type = sol().registry().new_usertype<parameters_manager>("parameters", "new", sol::no_constructor);
	parameters_type["add"] = &parameters_manager::add;
	parameters_type["lookup"] = &parameters_manager::lookup;


/*  video_manager library
 *
 * manager:machine():video()
 *
 * video:begin_recording([opt] filename, [opt] format) - start AVI recording to filename if given or default
 * video:end_recording() - stop AVI recording
 * video:is_recording() - get recording status
 * video:snapshot() - save shot of all screens
 * video:skip_this_frame() - is current frame going to be skipped
 * video:speed_factor() - get speed factor
 * video:speed_percent() - get percent from realtime
 * video:frame_update() - render a frame
 * video:size() - get width and height of snapshot bitmap in pixels
 * video:pixels() - get binary bitmap of all screens as string
 *
 * video.frameskip - current frameskip
 * video.throttled - throttle state
 * video.throttle_rate - throttle rate
 */

	auto video_type = sol().registry().new_usertype<video_manager>("video", "new", sol::no_constructor);
	video_type.set("begin_recording", sol::overload(
		[this](video_manager &vm, const char *filename, const char *format_string) {
			std::string fn = process_snapshot_filename(machine(), filename);
			movie_recording::format format = s_movie_recording_format_parser(format_string);
			vm.begin_recording(fn.c_str(), format);
		},
		[this](video_manager &vm, const char *filename) {
			std::string fn = process_snapshot_filename(machine(), filename);
			vm.begin_recording(fn.c_str(), movie_recording::format::AVI);
		},
		[](video_manager &vm) {
			vm.begin_recording(nullptr, movie_recording::format::AVI);
		}));
	video_type.set("end_recording", [this](video_manager &vm) {
			if(!vm.is_recording())
			{
				machine().logerror("[luaengine] No active recording to stop\n");
				return;
			}
			vm.end_recording();
		});
	video_type.set("snapshot", &video_manager::save_active_screen_snapshots);
	video_type.set("is_recording", &video_manager::is_recording);
	video_type.set("skip_this_frame", &video_manager::skip_this_frame);
	video_type.set("speed_factor", &video_manager::speed_factor);
	video_type.set("speed_percent", &video_manager::speed_percent);
	video_type.set("effective_frameskip", &video_manager::effective_frameskip);
	video_type.set("frame_update", &video_manager::frame_update);
	video_type.set("size", [](video_manager &vm) {
			s32 width, height;
			vm.compute_snapshot_size(width, height);
			return std::tuple<s32, s32>(width, height);
		});
	video_type.set("pixels", [](video_manager &vm, sol::this_state s) {
			lua_State *L = s;
			luaL_Buffer buff;
			s32 width, height;
			vm.compute_snapshot_size(width, height);
			int size = width * height * 4;
			u32 *ptr = (u32 *)luaL_buffinitsize(L, &buff, size);
			vm.pixels(ptr);
			luaL_pushresultsize(&buff, size);
			return sol::make_reference(L, sol::stack_reference(L, -1));
		});
	video_type.set("frameskip", sol::property(&video_manager::frameskip, &video_manager::set_frameskip));
	video_type.set("throttled", sol::property(&video_manager::throttled, &video_manager::set_throttled));
	video_type.set("throttle_rate", sol::property(&video_manager::throttle_rate, &video_manager::set_throttle_rate));


/*  sound_manager library
 *
 * manager:machine():sound()
 *
 * sound:start_recording() - begin audio recording
 * sound:stop_recording() - end audio recording
 * sound:ui_mute(turn_off) - turns on/off UI sound
 * sound:system_mute() - turns on/off system sound
 * sound:samples() - get current audio buffer contents in binary form as string (updates 50 times per second)
 *
 * sound.attenuation - sound attenuation
 */

	auto sound_type = sol().registry().new_usertype<sound_manager>("sound", "new", sol::no_constructor);
	sound_type.set("start_recording", &sound_manager::start_recording);
	sound_type.set("stop_recording", &sound_manager::stop_recording);
	sound_type.set("ui_mute", &sound_manager::ui_mute);
	sound_type.set("debugger_mute", &sound_manager::debugger_mute);
	sound_type.set("system_mute", &sound_manager::system_mute);
	sound_type.set("samples", [](sound_manager &sm, sol::this_state s) {
			lua_State *L = s;
			luaL_Buffer buff;
			s32 count = sm.sample_count() * 2 * 2; // 2 channels, 2 bytes per sample
			s16 *ptr = (s16 *)luaL_buffinitsize(L, &buff, count);
			sm.samples(ptr);
			luaL_pushresultsize(&buff, count);
			return sol::make_reference(L, sol::stack_reference(L, -1));
		});
	sound_type.set("attenuation", sol::property(&sound_manager::attenuation, &sound_manager::set_attenuation));


/* screen_device library
 *
 * manager:machine().screens[screen_tag]
 *
 * screen:draw_box(x1, y1, x2, y2, fillcol, linecol) - draw box from (x1, y1)-(x2, y2) colored linecol
 *                                                     filled with fillcol, color is 32bit argb
 * screen:draw_line(x1, y1, x2, y2, linecol) - draw line from (x1, y1)-(x2, y2) colored linecol
 * screen:draw_text(x || justify, y, message, [opt] fgcolor, [opt] bgcolor) - draw message at (x, y) or at line y
 *                                                                            with left/right/center justification
 * screen:height() - screen height
 * screen:width() - screen width
 * screen:orientation() - screen angle, flipx, flipy
 * screen:refresh() - screen refresh rate in Hz
 * screen:refresh_attoseconds() - screen refresh rate in attoseconds
 * screen:snapshot([opt] filename) - save snap shot
 * screen:type() - screen drawing type
 * screen:frame_number() - screen frame count
 * screen:name() - screen device full name
 * screen:shortname() - screen device short name
 * screen:tag() - screen device tag
 * screen:xscale() - screen x scale factor
 * screen:yscale() - screen y scale factor
 * screen:pixel(x, y) - get pixel at (x, y) as packed RGB in a u32
 * screen:pixels() - get whole screen binary bitmap as string
 * screen:time_until_pos(vpos, hpos) - get the time until this screen pos is reached
 */

	auto screen_dev_type = sol().registry().new_usertype<screen_device>("screen_dev", "new", sol::no_constructor);
	screen_dev_type.set("draw_box", [](screen_device &sdev, float x1, float y1, float x2, float y2, uint32_t bgcolor, uint32_t fgcolor) {
			int sc_width = sdev.visible_area().width();
			int sc_height = sdev.visible_area().height();
			x1 = std::min(std::max(0.0f, x1), float(sc_width-1)) / float(sc_width);
			y1 = std::min(std::max(0.0f, y1), float(sc_height-1)) / float(sc_height);
			x2 = std::min(std::max(0.0f, x2), float(sc_width-1)) / float(sc_width);
			y2 = std::min(std::max(0.0f, y2), float(sc_height-1)) / float(sc_height);
			mame_machine_manager::instance()->ui().draw_outlined_box(sdev.container(), x1, y1, x2, y2, fgcolor, bgcolor);
		});
	screen_dev_type.set("draw_line", [](screen_device &sdev, float x1, float y1, float x2, float y2, uint32_t color) {
			int sc_width = sdev.visible_area().width();
			int sc_height = sdev.visible_area().height();
			x1 = std::min(std::max(0.0f, x1), float(sc_width-1)) / float(sc_width);
			y1 = std::min(std::max(0.0f, y1), float(sc_height-1)) / float(sc_height);
			x2 = std::min(std::max(0.0f, x2), float(sc_width-1)) / float(sc_width);
			y2 = std::min(std::max(0.0f, y2), float(sc_height-1)) / float(sc_height);
			sdev.container().add_line(x1, y1, x2, y2, UI_LINE_WIDTH, rgb_t(color), PRIMFLAG_BLENDMODE(BLENDMODE_ALPHA));
		});
	screen_dev_type.set("draw_text", [this](screen_device &sdev, sol::object xobj, float y, const char *msg, sol::object color, sol::object bcolor) {
			int sc_width = sdev.visible_area().width();
			int sc_height = sdev.visible_area().height();
			auto justify = ui::text_layout::LEFT;
			float x = 0;
			if(xobj.is<float>())
			{
				x = std::min(std::max(0.0f, xobj.as<float>()), float(sc_width-1)) / float(sc_width);
				y = std::min(std::max(0.0f, y), float(sc_height-1)) / float(sc_height);
			}
			else if(xobj.is<const char *>())
			{
				justify = s_text_justify_parser(xobj.as<const char *>());
			}
			else
			{
				luaL_error(m_lua_state, "Error in param 1 to draw_text");
				return;
			}
			rgb_t textcolor = mame_machine_manager::instance()->ui().colors().text_color();
			rgb_t bgcolor = 0;
			if(color.is<uint32_t>())
				textcolor = rgb_t(color.as<uint32_t>());
			if(bcolor.is<uint32_t>())
				bgcolor = rgb_t(bcolor.as<uint32_t>());
			mame_machine_manager::instance()->ui().draw_text_full(sdev.container(), msg, x, y, (1.0f - x),
								justify, ui::text_layout::WORD, mame_ui_manager::OPAQUE_, textcolor, bgcolor);
		});
	screen_dev_type.set("height", [](screen_device &sdev) { return sdev.visible_area().height(); });
	screen_dev_type.set("width", [](screen_device &sdev) { return sdev.visible_area().width(); });
	screen_dev_type.set("orientation", [](screen_device &sdev) {
			uint32_t flags = sdev.orientation();
			int rotation_angle = 0;
			switch (flags)
			{
				case ORIENTATION_FLIP_X:
					rotation_angle = 0;
					break;
				case ORIENTATION_SWAP_XY:
				case ORIENTATION_SWAP_XY|ORIENTATION_FLIP_X:
					rotation_angle = 90;
					break;
				case ORIENTATION_FLIP_Y:
				case ORIENTATION_FLIP_X|ORIENTATION_FLIP_Y:
					rotation_angle = 180;
					break;
				case ORIENTATION_SWAP_XY|ORIENTATION_FLIP_Y:
				case ORIENTATION_SWAP_XY|ORIENTATION_FLIP_X|ORIENTATION_FLIP_Y:
					rotation_angle = 270;
					break;
			}
			return std::tuple<int, bool, bool>(rotation_angle, flags & ORIENTATION_FLIP_X, flags & ORIENTATION_FLIP_Y);
		});
	screen_dev_type.set("refresh", [](screen_device &sdev) { return ATTOSECONDS_TO_HZ(sdev.refresh_attoseconds()); });
	screen_dev_type.set("refresh_attoseconds", [](screen_device &sdev) { return sdev.refresh_attoseconds(); });
	screen_dev_type.set("snapshot", [this](screen_device &sdev, sol::object filename) -> sol::object {
			std::string snapstr;
			bool is_absolute_path = false;
			if (filename.is<const char *>())
			{
				// a filename was specified; if it isn't absolute postprocess it
				snapstr = process_snapshot_filename(machine(), filename.as<const char *>());
				is_absolute_path = osd_is_absolute_path(snapstr);
			}

			// open the file
			emu_file file(is_absolute_path ? "" : machine().options().snapshot_directory(), OPEN_FLAG_WRITE | OPEN_FLAG_CREATE | OPEN_FLAG_CREATE_PATHS);
			osd_file::error filerr;
			if (!snapstr.empty())
				filerr = file.open(snapstr);
			else
				filerr = machine().video().open_next(file, "png");
			if (filerr != osd_file::error::NONE)
				return sol::make_object(sol(), filerr);

			// and save the snapshot
			machine().video().save_snapshot(&sdev, file);
			return sol::make_object(sol(), sol::lua_nil);
		});
	screen_dev_type.set("type", [](screen_device &sdev) {
			switch (sdev.screen_type())
			{
				case SCREEN_TYPE_RASTER:  return "raster"; break;
				case SCREEN_TYPE_VECTOR:  return "vector"; break;
				case SCREEN_TYPE_LCD:     return "lcd"; break;
				case SCREEN_TYPE_SVG:     return "svg"; break;
				default: break;
			}
			return "unknown";
		});
	screen_dev_type.set("frame_number", &screen_device::frame_number);
	screen_dev_type.set("name", &screen_device::name);
	screen_dev_type.set("shortname", &screen_device::shortname);
	screen_dev_type.set("tag", &screen_device::tag);
	screen_dev_type.set("xscale", &screen_device::xscale);
	screen_dev_type.set("yscale", &screen_device::yscale);
	screen_dev_type.set("pixel", [](screen_device &sdev, float x, float y) { return sdev.pixel((s32)x, (s32)y); });
	screen_dev_type.set("pixels", [](screen_device &sdev, sol::this_state s) {
			lua_State *L = s;
			const rectangle &visarea = sdev.visible_area();
			luaL_Buffer buff;
			int size = visarea.height() * visarea.width() * 4;
			u32 *ptr = (u32 *)luaL_buffinitsize(L, &buff, size);
			sdev.pixels(ptr);
			luaL_pushresultsize(&buff, size);
			return sol::make_reference(L, sol::stack_reference(L, -1));
		});
	screen_dev_type.set("time_until_pos", [](screen_device &sdev, int vpos, int hpos) { return sdev.time_until_pos(vpos, hpos).as_double(); });


/*  mame_ui_manager library
 *
 * manager:ui()
 *
 * ui:is_menu_active() - ui menu state
 * ui:options() - ui core_options
 * ui:get_line_height() - current ui font height
 * ui:get_string_width(str, scale) - get str width with ui font at scale factor of current font size
 * ui:get_char_width(char) - get width of utf8 glyph char with ui font
 * ui:set_aggressive_input_focus(bool)
 *
 * ui.single_step
 * ui.show_fps - fps display enabled
 * ui.show_profiler - profiler display enabled
 */

	auto ui_type = sol().registry().new_usertype<mame_ui_manager>("ui", "new", sol::no_constructor);
	ui_type.set("is_menu_active", &mame_ui_manager::is_menu_active);
	ui_type.set("options", [](mame_ui_manager &m) { return static_cast<core_options *>(&m.options()); });
	ui_type.set("show_fps", sol::property(&mame_ui_manager::show_fps, &mame_ui_manager::set_show_fps));
	ui_type.set("show_profiler", sol::property(&mame_ui_manager::show_profiler, &mame_ui_manager::set_show_profiler));
	ui_type.set("single_step", sol::property(&mame_ui_manager::single_step, &mame_ui_manager::set_single_step));
	ui_type.set("get_line_height", &mame_ui_manager::get_line_height);
	ui_type.set("get_string_width", &mame_ui_manager::get_string_width);
	// sol converts char32_t to a string
	ui_type.set("get_char_width", [](mame_ui_manager &m, uint32_t utf8char) { return m.get_char_width(utf8char); });
	ui_type.set("set_aggressive_input_focus", [](mame_ui_manager &m, bool aggressive_focus) { osd_set_aggressive_input_focus(aggressive_focus); });


/*  device_state_entry library
 *
 * manager:machine().devices[device_tag].state[state_name]
 *
 * state:name() - get device state name
 * state:is_visible() - is state visible in debugger
 * state:is_divider() - is state a divider
 *
 * state.value - get device state value
 */

	auto dev_state_type = sol().registry().new_usertype<device_state_entry>("dev_state", "new", sol::no_constructor);
	dev_state_type.set("name", &device_state_entry::symbol);
	dev_state_type.set("value", sol::property(
		[this](device_state_entry &entry) -> uint64_t {
			device_state_interface *state = entry.parent_state();
			if(state)
			{
				machine().save().dispatch_presave();
				return state->state_int(entry.index());
			}
			return 0;
		},
		[this](device_state_entry &entry, uint64_t val) {
			device_state_interface *state = entry.parent_state();
			if(state)
			{
				state->set_state_int(entry.index(), val);
				machine().save().dispatch_presave();
			}
		}));
	dev_state_type.set("is_visible", &device_state_entry::visible);
	dev_state_type.set("is_divider", &device_state_entry::divider);


/*  rom_entry library
 *
 * manager:machine().devices[device_tag].roms[rom]
 *
 * rom:name()
 * rom:hashdata() - see hash.h
 * rom:offset()
 * rom:length()
 * rom:flags() - see romentry.h
 */

	auto rom_entry_type = sol().registry().new_usertype<rom_entry>("rom_entry", "new", sol::no_constructor);
	rom_entry_type.set("name", &rom_entry::name);
	rom_entry_type.set("hashdata", &rom_entry::hashdata);
	rom_entry_type.set("offset", &rom_entry::get_offset);
	rom_entry_type.set("length", &rom_entry::get_length);
	rom_entry_type.set("flags", &rom_entry::get_flags);


/*  output_manager library
 *
 * manager:machine():outputs()
 *
 * outputs:set_value(name, val) - set output name to val
 * outputs:set_indexed_value(index, val) - set output index to val
 * outputs:get_value(name) - get output name value
 * outputs:get_indexed_value(index) - get output index value
 * outputs:name_to_id(name) - get index for name
 * outputs:id_to_name(index) - get name for index
 */

	auto output_type = sol().registry().new_usertype<output_manager>("output", "new", sol::no_constructor);
	output_type.set("set_value", &output_manager::set_value);
	output_type.set("set_indexed_value", [](output_manager &o, char const *basename, int index, int value) {
			o.set_value(util::string_format("%s%d", basename, index).c_str(), value);
		});
	output_type.set("get_value", &output_manager::get_value);
	output_type.set("get_indexed_value", [](output_manager &o, char const *basename, int index) {
			return o.get_value(util::string_format("%s%d", basename, index).c_str());
		});
	output_type.set("name_to_id", &output_manager::name_to_id);
	output_type.set("id_to_name", &output_manager::id_to_name);


/*  device_image_interface library
 *
 * manager:machine().images[image_type]
 *
 * image:exists()
 * image:filename() - full path to the image file
 * image:longname()
 * image:manufacturer()
 * image:year()
 * image:software_list_name()
 * image:image_type_name() - floppy/cart/cdrom/tape/hdd etc
 * image:load(filename)
 * image:load_software(softlist_name)
 * image:unload()
 * image:create()
 * image:crc()
 * image:display()
 *
 * image.device - get associated device_t
 * image.instance_name
 * image.brief_instance_name
 * image.software_parent
 * image.is_readable
 * image.is_writeable
 * image.is_creatable
 * image.is_reset_on_load
 * image.must_be_loaded
 */

	auto image_type = sol().registry().new_usertype<device_image_interface>("image", "new", sol::no_constructor);
	image_type.set("exists", &device_image_interface::exists);
	image_type.set("filename", &device_image_interface::filename);
	image_type.set("longname", &device_image_interface::longname);
	image_type.set("manufacturer", &device_image_interface::manufacturer);
	image_type.set("year", &device_image_interface::year);
	image_type.set("software_list_name", &device_image_interface::software_list_name);
	image_type.set("software_parent", sol::property([](device_image_interface &di) {
			const software_info *si = di.software_entry();
			return si ? si->parentname() : "";
		}));
	image_type.set("image_type_name", &device_image_interface::image_type_name);
	image_type.set("load", &device_image_interface::load);
	image_type.set("load_software", static_cast<image_init_result (device_image_interface::*)(const std::string &)>(&device_image_interface::load_software));
	image_type.set("unload", &device_image_interface::unload);
	image_type.set("create", [](device_image_interface &di, const std::string &filename) { return di.create(filename); });
	image_type.set("crc", &device_image_interface::crc);
	image_type.set("display", [](device_image_interface &di) { return di.call_display(); });
	image_type.set("device", sol::property(static_cast<device_t & (device_image_interface::*)()>(&device_image_interface::device)));
	image_type.set("instance_name", sol::property(&device_image_interface::instance_name));
	image_type.set("brief_instance_name", sol::property(&device_image_interface::brief_instance_name));
	image_type.set("is_readable", sol::property(&device_image_interface::is_readable));
	image_type.set("is_writeable", sol::property(&device_image_interface::is_writeable));
	image_type.set("is_creatable", sol::property(&device_image_interface::is_creatable));
	image_type.set("is_reset_on_load", sol::property(&device_image_interface::is_reset_on_load));
	image_type.set("must_be_loaded", sol::property(&device_image_interface::must_be_loaded));

/*  device_slot_interface library
 *
 * manager:machine().slots[slot_name]
 *
 * slot.fixed - whether this slot is fixed, and hence not selectable by the user
 * slot.has_selectable_options - does this slot have any selectable options at all?
 * slot.default_option - returns the default option if one exists
 * slot.options[] - get options table (k=name, v=device_slot_interface::slot_option)
 */

	auto slot_type = sol().registry().new_usertype<device_slot_interface>("slot", "new", sol::no_constructor);
	slot_type["fixed"] = sol::property(&device_slot_interface::fixed);
	slot_type["has_selectable_options"] = sol::property(&device_slot_interface::has_selectable_options);
	slot_type["default_option"] = sol::property(&device_slot_interface::default_option);
	slot_type["options"] = sol::property([](const device_slot_interface &slot) { return standard_tag_object_ptr_map<device_slot_interface::slot_option>(slot.option_list()); });


/*  device_slot_interface::slot_option library
 *
 * manager:machine().slots[slot_name].options[option_name]
 *
 * slot_option.selectable - is this item selectable by the user?
 * slot_option.default_bios - the default bios for this option
 * slot_option.clock - the clock speed associated with this option
 */

	auto dislot_option_type = sol().registry().new_usertype<device_slot_interface::slot_option>("dislot_option", "new", sol::no_constructor);
	dislot_option_type["selectable"] = sol::property(&device_slot_interface::slot_option::selectable);
	dislot_option_type["default_bios"] = sol::property(static_cast<const char *(device_slot_interface::slot_option::*)() const>(&device_slot_interface::slot_option::default_bios));
	dislot_option_type["clock"] = sol::property(static_cast<u32 (device_slot_interface::slot_option:: *)() const>(&device_slot_interface::slot_option::clock));


/*  cassette_image_device
 *
 * device.cassette
 *
 * cass:play()
 * cass:stop()
 * cass:record()
 * cass:forward() - forward play direction
 * cass:reverse() - reverse play direction
 * cass:seek(time, origin) - seek time sec from origin: "set", "cur", "end"
 *
 * cass.is_stopped
 * cass.is_playing
 * cass.is_recording
 * cass.motor_state
 * cass.speaker_state
 * cass.position
 * cass.length
 * cass.image - get the device_image_interface for this cassette device
 */

	auto cass_type = sol().registry().new_usertype<cassette_image_device>("cassette", sol::no_constructor);
	cass_type["stop"] = [] (cassette_image_device &c) { c.change_state(CASSETTE_STOPPED, CASSETTE_MASK_UISTATE); };
	cass_type["play"] = [] (cassette_image_device &c) { c.change_state(CASSETTE_PLAY, CASSETTE_MASK_UISTATE); };
	cass_type["record"] = [] (cassette_image_device &c) { c.change_state(CASSETTE_RECORD, CASSETTE_MASK_UISTATE); };
	cass_type["is_stopped"] = sol::property(&cassette_image_device::is_stopped);
	cass_type["is_playing"] = sol::property(&cassette_image_device::is_playing);
	cass_type["is_recording"] = sol::property(&cassette_image_device::is_recording);
	cass_type["motor_state"] = sol::property(&cassette_image_device::motor_on, &cassette_image_device::set_motor);
	cass_type["speaker_state"] = sol::property(&cassette_image_device::speaker_on, &cassette_image_device::set_speaker);
	cass_type["position"] = sol::property(&cassette_image_device::get_position);
	cass_type["length"] = sol::property([] (cassette_image_device &c) { if (c.exists()) return c.get_length(); return 0.0; });
	cass_type["forward"] = &cassette_image_device::go_forward;
	cass_type["reverse"] = &cassette_image_device::go_reverse;
	cass_type["seek"] = [] (cassette_image_device &c, double time, const char* origin) { if (c.exists()) c.seek(time, s_seek_parser(origin)); };
	cass_type["image"] = sol::property([] (cassette_image_device &c) { return dynamic_cast<device_image_interface *>(&c); });


/*  mame_machine_manager library
 *
 * manager
 * mame_manager - alias of manager
 *
 * manager:machine() - running machine
 * manager:options() - emu options
 * manager:plugins() - plugin options
 * manager:ui() - mame ui manager
 */

	sol().registry().new_usertype<mame_machine_manager>("manager", "new", sol::no_constructor,
			"machine", &machine_manager::machine,
			"options", &machine_manager::options,
			"plugins", [this](mame_machine_manager &m) {
				sol::table table = sol().create_table();
				for (auto &curentry : m.plugins().plugins())
				{
					sol::table plugin_table = sol().create_table();
					plugin_table["name"] = curentry.m_name;
					plugin_table["description"] = curentry.m_description;
					plugin_table["type"] = curentry.m_type;
					plugin_table["directory"] = curentry.m_directory;
					plugin_table["start"] = curentry.m_start;
					table[curentry.m_name] = plugin_table;
				}
				return table;
			},
			"ui", &mame_machine_manager::ui);
	sol()["manager"] = std::ref(*mame_machine_manager::instance());
	sol()["mame_manager"] = std::ref(*mame_machine_manager::instance());


	// set up other user types
	initialize_debug();
	initialize_input();
	initialize_memory();
	initialize_render();
}

//-------------------------------------------------
//  frame_hook - called at each frame refresh, used to draw a HUD
//-------------------------------------------------
bool lua_engine::frame_hook()
{
	return execute_function("LUA_ON_FRAME_DONE");
}

//-------------------------------------------------
//  close - close and cleanup of lua engine
//-------------------------------------------------

void lua_engine::close()
{
	m_sol_state.reset();
	if (m_lua_state)
	{
		lua_settop(m_lua_state, 0);  /* clear stack */
		lua_close(m_lua_state);
		m_lua_state = nullptr;
	}
}

void lua_engine::resume(void *ptr, int nparam)
{
	lua_rawgeti(m_lua_state, LUA_REGISTRYINDEX, nparam);
	lua_State *L = lua_tothread(m_lua_state, -1);
	lua_pop(m_lua_state, 1);
	int stat = lua_resume(L, nullptr, 0);
	if((stat != LUA_OK) && (stat != LUA_YIELD))
	{
		osd_printf_error("[LUA ERROR] in resume: %s\n", lua_tostring(L, -1));
		lua_pop(L, 1);
	}
	luaL_unref(m_lua_state, LUA_REGISTRYINDEX, nparam);
}

void lua_engine::run(sol::load_result res)
{
	if(res.valid())
	{
		auto ret = invoke(res.get<sol::protected_function>());
		if(!ret.valid())
		{
			sol::error err = ret;
			osd_printf_error("[LUA ERROR] in run: %s\n", err.what());
		}
	}
	else
		osd_printf_error("[LUA ERROR] %d loading Lua script\n", (int)res.status());
}

//-------------------------------------------------
//  execute - load and execute script
//-------------------------------------------------

void lua_engine::load_script(const char *filename)
{
	run(sol().load_file(filename));
}

//-------------------------------------------------
//  execute_string - execute script from string
//-------------------------------------------------

void lua_engine::load_string(const char *value)
{
	run(sol().load(value));
}