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
#[cfg(feature = "compiler")]
pub mod compile;
pub mod ffi;
mod libs;
mod memory;
mod threads;
mod userdata;
use std::{
any::Any,
cell::Cell,
ffi::{c_int, c_uint, c_void, CStr, CString},
ptr::{null, null_mut},
rc::Rc,
slice,
};
use ffi::{
luauconf::{LUAI_MAXCSTACK, LUA_MEMORY_CATEGORIES},
prelude::*,
};
use memory::{luau_alloc_cb, DefaultLuauAllocator};
use userdata::{
drop_userdata, dtor_rs_luau_userdata_callback, Userdata, UserdataBorrowError, UserdataRef,
UserdataRefMut, UD_TAG,
};
pub use ffi::prelude::LuauStatus;
pub use libs::LuauLibs;
pub use memory::LuauAllocator;
pub use threads::LuauThread;
macro_rules! luau_stack_precondition {
($cond:expr) => {
assert!(
$cond,
"Stack indicies should not exceed the top of the stack or extend below."
)
};
}
struct AssociatedData {
main_thread_rc: Rc<Cell<bool>>,
allocator: Box<dyn LuauAllocator>,
app_data: Option<Box<dyn Any>>,
}
#[cfg(feature = "codegen")]
/// Returns true if codegen is supported for the given platform
pub fn codegen_supported() -> bool {
unsafe { luau_codegen_supported() == 1 }
}
/// Main struct implementing luau functionality
pub struct Luau {
owned: bool,
state: *mut _LuaState,
}
impl Luau {
unsafe fn new_state(allocator: impl LuauAllocator + 'static) -> *mut _LuaState {
let associated_data = Box::new(AssociatedData {
main_thread_rc: Rc::new(Cell::new(true)),
app_data: None,
allocator: Box::new(allocator),
});
let state = lua_newstate(luau_alloc_cb, Box::into_raw(associated_data) as _);
lua_setuserdatadtor(state, UD_TAG, Some(dtor_rs_luau_userdata_callback));
(*lua_callbacks(state)).panic = Some(fatal_error_handler);
state
}
pub fn new(allocator: impl LuauAllocator + 'static) -> Self {
let state = unsafe { Self::new_state(allocator) };
if state.is_null() {
panic!("Initialization of Luau failed");
}
Self { owned: true, state }
}
#[cfg(feature = "codegen")]
/// Enables codegen for the given state
pub fn enable_codegen(&self) {
unsafe {
luau_codegen_create(self.state);
}
}
/// Creates a Luau struct from a raw state pointer
///
/// # Safety
/// The pointer must be a valid Luau state created by `Luau::new`
pub unsafe fn from_ptr(state: *mut _LuaState) -> Self {
Self {
owned: false,
state,
}
}
/// Creates a Luau struct from a raw state pointer
///
/// # Safety
/// The pointer must be a valid Luau state and must not alias a Luau struct
pub unsafe fn from_ptr_owned(state: *mut _LuaState) -> Self {
Self { owned: true, state }
}
const ASSOCIATED_DATA_ERROR: &str = "Expected associated data structure";
pub(crate) fn get_associated(&self) -> &AssociatedData {
unsafe {
let mut ptr: *const AssociatedData = null();
lua_getallocf(self.state, &raw mut ptr as _);
ptr.as_ref().expect(Self::ASSOCIATED_DATA_ERROR)
}
}
pub(crate) fn get_associated_mut(&self) -> *mut AssociatedData {
unsafe {
let mut ptr: *mut AssociatedData = null_mut();
lua_getallocf(self.state, &raw mut ptr as _);
assert!(!ptr.is_null(), "{}", Self::ASSOCIATED_DATA_ERROR);
ptr
}
}
pub fn get_app_data<T: Any>(&self) -> Option<&T> {
self.get_associated()
.app_data
.as_ref()
.and_then(|v| v.downcast_ref())
}
/// Sets the associated app data for the Luau state returning the previous value
pub fn set_app_data<T: Any>(&self, ud: Option<T>) -> Option<Box<dyn Any>> {
let associated = unsafe { &mut *self.get_associated_mut() };
if let Some(v) = ud {
let boxed_data = Box::new(v);
associated.app_data.replace(boxed_data)
} else {
associated.app_data.take()
}
}
pub fn load_libs(&self, lib: LuauLibs) {
macro_rules! load_lib {
($func:ident) => {
unsafe {
self.push_raw_function(
$func,
Some(&CString::new(stringify!($func)).unwrap()),
0,
None,
);
self.push_string("");
self.call(1, 0);
};
};
($idnt:expr, $func:ident) => {
unsafe {
self.push_raw_function(
$func,
Some(&CString::new(stringify!($func)).unwrap()),
0,
None,
);
self.push_string($idnt);
self.call(1, 0);
};
};
}
if lib.has(LuauLibs::ALL_LIBS) {
unsafe { luaL_openlibs(self.state) };
return;
}
if lib.has(LuauLibs::LIB_BASE) {
load_lib!(luaopen_base);
}
if lib.has(LuauLibs::LIB_COROUTINE) {
load_lib!(LUA_COLIBNAME, luaopen_coroutine);
}
if lib.has(LuauLibs::LIB_TABLE) {
load_lib!(LUA_TABLIBNAME, luaopen_table);
}
if lib.has(LuauLibs::LIB_OS) {
load_lib!(LUA_OSLIBNAME, luaopen_os);
}
if lib.has(LuauLibs::LIB_STRING) {
load_lib!(LUA_STRLIBNAME, luaopen_string);
}
if lib.has(LuauLibs::LIB_MATH) {
load_lib!(LUA_MATHLIBNAME, luaopen_math);
}
if lib.has(LuauLibs::LIB_DEBUG) {
load_lib!(LUA_DBLIBNAME, luaopen_debug);
}
if lib.has(LuauLibs::LIB_UTF8) {
load_lib!(LUA_UTF8LIBNAME, luaopen_utf8);
}
if lib.has(LuauLibs::LIB_BIT32) {
load_lib!(LUA_BITLIBNAME, luaopen_bit32);
}
if lib.has(LuauLibs::LIB_BUFFER) {
load_lib!(LUA_BUFFERLIBNAME, luaopen_buffer);
}
}
#[inline]
pub fn to_ptr(&self) -> *mut _LuaState {
self.state
}
#[inline]
pub fn top(&self) -> c_int {
unsafe { lua_gettop(self.state) }
}
/// Returns the status of the Luau state
pub fn status(&self) -> LuauStatus {
unsafe { lua_status(self.state) }
}
/// Yields the luau state with the number of results
///
/// Should be used as the end expression or a return from a function as this returns `-1`
pub fn yield_luau(&self, nresults: c_int) -> c_int {
assert!(
self.top() >= nresults,
"The number of yield returns must not exceed the stack size"
);
unsafe { lua_yield(self.state, nresults) }
}
/// Breaks the luau state for the purposes of a debug interrupt
///
/// Should be used as the end expression or a return from a function as this returns `-1`
pub fn break_luau(&self) -> c_int {
unsafe { lua_break(self.state) }
}
/// Produces an error with the value on the top of the stack
pub fn error(&self) -> c_int {
luau_stack_precondition!(self.check_index(-1));
// SAFETY: a value on the top of the stack exists as verified by the precondition
unsafe { lua_error(self.state) }
}
/// Returns the type of a luau value at `idx`
pub fn type_of(&self, idx: c_int) -> LuauType {
luau_stack_precondition!(self.check_index(idx));
unsafe { lua_type(self.state, idx) }
}
/// Pops `n` values from the stack
pub fn pop(&self, n: c_int) {
// assert that the set position is not greater than the top
luau_stack_precondition!(self.check_index(-n));
// SAFETY: -n is validated by the precondition
unsafe { lua_settop(self.state, -(n + 1)) }
}
/// Returns an upvalue index for the specified upvalue index
pub fn upvalue(&self, uv_idx: c_int) -> c_int {
lua_upvalueindex(uv_idx)
}
/// Sets the memory category for all allocations taking place after its set
pub fn set_memory_category(&self, cat: c_int) {
assert!(
cat < LUA_MEMORY_CATEGORIES,
"Memory category index must not exceed {LUA_MEMORY_CATEGORIES}"
);
unsafe {
lua_setmemcat(self.state, cat);
}
}
pub fn check_index(&self, idx: c_int) -> bool {
if idx <= LUA_REGISTRYINDEX {
return true;
}
if idx == 0 {
return false;
}
let top = self.top();
let idx = if idx < 0 {
// "subtract" the top (idx is negative)
top.wrapping_add(idx)
} else {
idx
};
if idx < LUA_GLOBALSINDEX {
// upvalue idx
return true;
}
// zero is acceptable here
idx >= 0 && // greater or equal to zero and
idx <= top && // lesser than or equal to the top and
idx < LUAI_MAXCSTACK // smaller than the maximum c stack
}
pub fn check_stack(&self, sz: c_int) -> bool {
unsafe { lua_checkstack(self.state, sz) == 1 }
}
#[inline]
pub fn registry(&self) -> c_int {
LUA_REGISTRYINDEX
}
#[inline]
pub fn globals(&self) -> c_int {
LUA_GLOBALSINDEX
}
pub fn check_args(&self, count: c_int, extra_message: Option<&CStr>) {
if self.top() >= count {
return;
}
unsafe {
luaL_argerrorL(
self.state,
count - self.top(),
extra_message.map(CStr::as_ptr).unwrap_or(null()),
);
}
}
/// Returns true if the value at `idx` is nil
pub fn is_nil(&self, idx: c_int) -> bool {
self.type_of(idx) == LuauType::LUA_TNIL
}
/// Pushes a nil value to the stack
pub fn push_nil(&self) {
luau_stack_precondition!(self.check_stack(1));
// SAFETY: stack size is validated by precondition
unsafe {
lua_pushnil(self.state);
}
}
/// Returns true if the value at `idx` is a bool, false otherwise
pub fn is_boolean(&self, idx: c_int) -> bool {
self.type_of(idx) == LuauType::LUA_TBOOLEAN
}
/// Returns true if the value at `idx` is not nil or false, otherwise returns false
pub fn to_boolean(&self, idx: c_int) -> bool {
luau_stack_precondition!(self.check_index(idx));
// SAFETY: idx is validated by the precondition
unsafe { lua_toboolean(self.state, idx) == 1 }
}
/// Pushes a boolean value to the Luau stack
pub fn push_boolean(&self, value: bool) {
luau_stack_precondition!(self.check_stack(1));
// SAFETY: stack size is validated by the precondition
unsafe {
lua_pushboolean(self.state, value as i32);
}
}
/// Returns true if the value at idx is a number, false otherwise
pub fn is_number(&self, idx: c_int) -> bool {
self.type_of(idx) == LuauType::LUA_TNUMBER
}
/// Pushes an integer onto the Luau stack
pub fn push_integer(&self, n: c_int) {
luau_stack_precondition!(self.check_stack(1));
// SAFETY: we have adequate stack space as checked by the precondition
unsafe {
lua_pushinteger(self.state, n);
}
}
/// Pushes an unsigned integer onto the Luau stack
pub fn push_unsigned_integer(&self, n: c_uint) {
luau_stack_precondition!(self.check_stack(1));
// SAFETY: we have adequate stack space as checked by the precondition
unsafe {
lua_pushunsigned(self.state, n);
}
}
/// Push a double into the Luau stack
pub fn push_number(&self, n: f64) {
// validate if the pushed index will not exceed the max C stack length
luau_stack_precondition!(self.check_stack(1));
// SAFETY: stack is appropriately sized, as checked by the precondition above
unsafe {
lua_pushnumber(self.state, n);
}
}
/// Gets/converts a Lua value at `idx` to a number.
///
/// Will convert a compatible string to a number
pub fn to_number(&self, idx: c_int) -> Option<f64> {
luau_stack_precondition!(self.check_index(idx));
let mut is_number = 0;
// SAFETY: idx is validated by the precondition and is therefore safe to access
let number = unsafe { lua_tonumberx(self.state, idx, &raw mut is_number) };
if is_number == 1 {
Some(number)
} else {
None
}
}
/// Returns true if the value at `idx` is a number, false otherwise
pub fn is_string(&self, idx: c_int) -> bool {
self.type_of(idx) == LuauType::LUA_TSTRING
}
/// Pushes a string to the top of the Luau stack
pub fn push_string(&self, str: impl AsRef<[u8]>) {
luau_stack_precondition!(self.check_stack(1));
let slice = str.as_ref();
// SAFETY: the stack size is checked by the precondition
unsafe {
lua_pushlstring(self.state, slice.as_ptr() as _, slice.len());
}
}
/// Gets or tries to coerce a Luau value at `idx` into a slice of u8s
pub fn to_str_slice(&self, idx: c_int) -> Option<&[u8]> {
luau_stack_precondition!(self.check_index(idx));
// needs to have a lifetime to bind the result on a lifetime to prevent use after frees
let mut len = 0;
// SAFETY: idx is validated by the precondition
let data = unsafe { lua_tolstring(self.state, idx, &mut len) };
if !data.is_null() {
// SAFETY: Luau can be trusted to return the correct len
unsafe { Some(std::slice::from_raw_parts(data as _, len)) }
} else {
None
}
}
/// Gets or tries to coerce a Luau value at `idx` into a str reference
pub fn to_str(&self, idx: c_int) -> Option<Result<&str, std::str::Utf8Error>> {
// preconditions are checked by to_string_slice
self.to_str_slice(idx).map(|v| std::str::from_utf8(v))
}
/// Gets or converts a Luau value at `idx` into a string with a reasonable format, will invoke __tostring metamethods.
pub fn convert_to_str_slice(&self, idx: c_int) -> &[u8] {
luau_stack_precondition!(self.check_index(idx));
unsafe {
let mut len = 0;
let data = luaL_tolstring(self.state, idx, &raw mut len);
if data.is_null() {
unreachable!("Luau string conversion returned NULL ptr");
} else {
std::slice::from_raw_parts(data as _, len)
}
}
}
/// Returns true if the userdata at `idx` is a userdata and is of type T
pub fn is_userdata<T: Any>(&self, idx: c_int) -> bool {
luau_stack_precondition!(self.check_index(idx));
// SAFETY: idx is validated by the precondition and the behavior of userdata is checked
unsafe {
let userdata_ptr: *mut Userdata<()> =
lua_touserdatatagged(self.state, idx, UD_TAG) as _;
!userdata_ptr.is_null() && (*userdata_ptr).is::<T>()
}
}
/// Returns true if the userdata at `idx` is any type of userdata
pub fn is_any_userdata<T: Any>(&self, idx: c_int) -> bool {
luau_stack_precondition!(self.check_index(idx));
// SAFETY: idx is validated by the precondition
unsafe { lua_isuserdata(self.state, idx) == 1 }
}
/// Pushes a value T as a userdata to Luau
pub fn push_userdata<T: Any>(&self, object: T) {
luau_stack_precondition!(self.check_stack(1));
// SAFETY: We allocate a DST as a userdata on a stack with the known proper size with our own tag.
// if the userdat allo
// if our type T has drop glue then we will set the dtor field which will be invoked
// we then construct a struct which has ownership of T
// we need the dtor field because the struct is opaque elsewhere
unsafe {
let userdata_ptr: *mut Userdata<T> =
lua_newuserdatatagged(self.state, size_of::<Userdata<T>>(), UD_TAG).cast();
let dtor = if std::mem::needs_drop::<T>() {
let fn_item: unsafe fn(*mut Userdata<T>) = drop_userdata::<T>;
Some(fn_item)
} else {
None
};
userdata_ptr.write(Userdata {
id: object.type_id(),
count_cell: Cell::new(0),
dtor,
inner: object,
});
}
}
fn get_userdata_ptr<T: Any>(&self, idx: c_int) -> Option<*mut Userdata<T>> {
luau_stack_precondition!(self.check_index(idx));
// SAFETY: We validate that the userdata at the checked idx is of the proper type T or null
unsafe {
let userdata_ptr: *mut Userdata<()> =
lua_touserdatatagged(self.state, idx, UD_TAG) as _;
if !userdata_ptr.is_null() && (*userdata_ptr).is::<T>() {
Some(userdata_ptr as _)
} else {
None
}
}
}
/// Returns a result with a ref to a userdata value of type T or an error if the userdata is already mutably borrowed.
///
/// Returns `None` if the value isn't a userdata or the userdata is not of type T.
pub fn try_borrow_userdata<T: Any>(
&self,
idx: c_int,
) -> Option<Result<UserdataRef<T>, UserdataBorrowError>> {
// SAFETY: We validate that the userdata at the checked idx is a userdata and a valid T through `get_userdata_ptr`
unsafe {
let userdata_ptr = self.get_userdata_ptr(idx)?;
Some(UserdataRef::try_from_ptr(userdata_ptr))
}
}
/// Gets a reference to a userdata value of type T, returning None if the value isn't a userdata or the userdata is not of type T.
///
/// Will panic if the userdata is already mutably borrowed
pub fn borrow_userdata<T: Any>(&self, idx: c_int) -> Option<UserdataRef<T>> {
self.try_borrow_userdata(idx).map(Result::unwrap)
}
/// Tries to get a mutable reference to a userdata value of type T. Returns a result with the ref or an error.
///
/// Returns `None` if the value is not of the correct type or if the value is already at idx.
pub fn try_borrow_userdata_mut<T: Any>(
&self,
idx: c_int,
) -> Option<Result<UserdataRefMut<T>, UserdataBorrowError>> {
// SAFETY: We validate that the userdata at the checked idx is a userdata and a valid T through `get_userdata_ptr`
unsafe {
let userdata_ptr = self.get_userdata_ptr(idx)?;
Some(UserdataRefMut::try_from_ptr(userdata_ptr))
}
}
/// Retrives a userdata of type T without performing a type check to determine if the inner type is really T
///
/// Will return None if the value at idx is not a userdata
///
/// # Safety
/// You need to know beforehand that the userdata here is of the correct type or has such a layout that the type requested is valid
pub unsafe fn get_userdata_unchecked<T: 'static>(&self, idx: c_int) -> Option<&mut T> {
luau_stack_precondition!(self.check_index(idx));
// SAFETY: we don't do any checking other than validating idx
unsafe { Some(&mut (*self.get_userdata_ptr(idx)?).inner) }
}
/// Returns true if the value at `idx` is a light userdata, it returns false otherwise.
pub fn is_lightuserdata(&self, idx: c_int) -> bool {
self.type_of(idx) == LuauType::LUA_TLIGHTUSERDATA
}
/// Returns an option of a raw pointer. Will be Some if the value at `idx` is a lightuserdata, None otherwise.
pub fn to_lightuserdata<T>(&self, idx: c_int) -> Option<*mut T> {
luau_stack_precondition!(self.check_index(idx));
// SAFETY: idx is checked by precondition
unsafe {
let ptr: *mut T = lua_tolightuserdata(self.state, idx).cast();
if ptr.is_null() {
None
} else {
Some(ptr)
}
}
}
/// Returns true if the Luau value at `idx` is a buffer, false otherwise
pub fn is_buffer(&self, idx: c_int) -> bool {
self.type_of(idx) == LuauType::LUA_TBUFFER
}
/// Creates a luau buffer of a provided size and pushes it on the stack
///
/// This will issue an error if the allocation cannot be performed
pub fn push_buffer(&mut self, size: usize) -> &mut [u8] {
luau_stack_precondition!(self.check_stack(1));
unsafe {
let ptr: *mut u8 = lua_newbuffer(self.state, size) as _;
std::slice::from_raw_parts_mut(ptr, size)
}
}
/// Pushes a slice to the Luau stack as a buffer
pub fn push_buffer_from_slice(&mut self, slice: impl AsRef<[u8]>) -> &mut [u8] {
// precondition is validated by push_buffer
let slice = slice.as_ref();
let buffer = self.push_buffer(slice.len());
buffer.copy_from_slice(slice);
buffer
}
/// Gets a Luau value at `idx` as a mutable slice of bytes
pub fn to_buffer(&mut self, idx: c_int) -> Option<&mut [u8]> {
luau_stack_precondition!(self.check_index(idx));
let mut len = 0;
// SAFETY: idx is validated by the precondition
let data: *mut u8 = unsafe { lua_tobuffer(self.state, idx, &mut len) as _ };
// will be null if the value is not a buffer
if !data.is_null() {
// SAFETY: Luau will report the right length
unsafe { Some(slice::from_raw_parts_mut(data, len)) }
} else {
None
}
}
/// Gets the pointer of a buffer value returning NULL if the value at `idx` is not a buffer
pub fn to_buffer_ptr(&self, idx: c_int, len: &mut usize) -> *mut c_void {
luau_stack_precondition!(self.check_index(idx));
// SAFETY: idx is validated by precondition
unsafe { lua_tobuffer(self.state, idx, len) }
}
/// Pushes an empty table to the Luau stack
pub fn create_table(&self) {
unsafe {
lua_createtable(self.state, 0, 0);
}
}
/// Pushes an empty table to the Luau stack with a preallocated array portion of `narr` and an associative portion of `nrec`
pub fn create_table_with_capacity(&self, narr: c_int, nrec: c_int) {
unsafe {
lua_createtable(self.state, narr, nrec);
}
}
pub fn shift(&self, to: c_int) {
luau_stack_precondition!(self.check_index(to));
unsafe {
lua_insert(self.state, to);
}
}
/// Makes a reference to the value at `idx` which can be retrieved from `get_reference`
pub fn reference(&self, idx: c_int) -> RefIndex {
luau_stack_precondition!(self.check_index(idx));
// SAFETY: idx is checked
unsafe { lua_ref(self.state, idx) }
}
/// Retrieves a reference from a RefIndex and pushes it to the top of the stack while returning the type's value
pub fn get_reference(&self, ref_index: RefIndex) -> LuauType {
luau_stack_precondition!(self.check_stack(1));
// SAFETY: stack size is checked
unsafe { lua_getref(self.state, ref_index) }
}
/// Removes a reference
pub fn unreference(&self, ref_index: RefIndex) {
unsafe {
lua_unref(self.state, ref_index);
}
}
/// Returns true if the value at `idx` is a table, false otherwise
pub fn is_table(&self, idx: c_int) -> bool {
self.type_of(idx) == LuauType::LUA_TTABLE
}
/// Sets t\[k\] = v where k is the field string, t is the table at idx and k is the value on the top of the stack
///
/// May invoke a __newindex metamethod
pub fn set_field(&self, idx: c_int, field: impl AsRef<[u8]>) {
luau_stack_precondition!(self.check_stack(1));
// bad hack
let idx = if idx < 0 && !lua_ispseudo(idx) && !(idx == -1 && self.top() == 1) {
idx - 1
} else {
idx
};
self.push_string(field);
self.shift(-2);
self.set_table(idx);
}
/// Sets t\[k\] = v where k is the field string, t is the table at idx and k is the value on the top of the stack
///
/// Will not invoke a __newindex metamethod
pub fn raw_set_field(&self, idx: c_int, field: &str) {
luau_stack_precondition!(self.check_stack(1));
let idx = if idx < 0 && !lua_ispseudo(idx) && !(idx == -1 && self.top() == 1) {
idx - 1
} else {
idx
};
self.push_string(field);
self.shift(-2);
self.raw_set_table(idx);
}
/// Sets the value of t\[k\] with the value at the top of the stack where t is at the index and k is the value beneath the top of the stack.
///
/// May invoke a __newindex metamethod
pub fn set_table(&self, idx: c_int) {
assert!(
self.top() >= 2,
"There must be a key and value on the stack to set table"
);
luau_stack_precondition!(self.check_index(idx));
// SAFETY: idx is validated by the precondition
unsafe {
lua_settable(self.state, idx);
}
}
/// Sets the value of t\[k\] with the value at the top of the stack where t is at the index and k is the value beneath the top of the stack.
///
/// Will not invoke a __newindex metamethod
pub fn raw_set_table(&self, idx: c_int) {
assert!(
self.top() >= 2,
"There must be a key and value on the stack to set table"
);
luau_stack_precondition!(self.check_index(idx));
// SAFETY: idx is validated by the precondition
unsafe {
lua_rawset(self.state, idx);
}
}
/// Gets t\[k\] where k is the field string where t is the table at idx.
///
/// May invoke a __index metamethod
pub fn get_field(&self, idx: c_int, field: impl AsRef<[u8]>) {
luau_stack_precondition!(self.check_index(idx));
luau_stack_precondition!(self.check_stack(1));
let idx = if idx < 0 && !lua_ispseudo(idx) {
idx - 1
} else {
idx
};
self.push_string(field);
self.get_table(idx);
}
/// Gets t\[k\] where k is the field string where t is the table at idx.
///
/// Will not invoke a __index metamethod
pub fn raw_get_field(&self, idx: c_int, field: impl AsRef<[u8]>) {
luau_stack_precondition!(self.check_index(idx));
luau_stack_precondition!(self.check_stack(1));
let idx = if idx < 0 && !lua_ispseudo(idx) {
idx - 1
} else {
idx
};
self.push_string(field);
self.raw_get_table(idx);
}
/// Gets the value of t\[k\] where t is the value at the index and k is the value on the top of the stack.
///
/// May invoke a __index metamethod
pub fn get_table(&self, idx: c_int) {
assert!(
self.top() >= 1,
"There must be a key on the stack to index the table"
);
luau_stack_precondition!(self.check_index(idx));
// SAFETY: idx is validated by the precondition
unsafe {
lua_gettable(self.state, idx);
}
}
/// Gets the value of t\[k\] where t is the value at the index and k is the value on the top of the stack.
///
/// Will not invoke a __index metamethod
pub fn raw_get_table(&self, idx: c_int) {
assert!(
self.top() >= 1,
"There must be a key on the stack to index the table"
);
luau_stack_precondition!(self.check_index(idx));
// SAFETY: idx is validated by the precondition
unsafe {
lua_rawget(self.state, idx);
}
}
/// Changes the readonly mode of a table at `idx` to the supplied boolean
pub fn set_readonly(&self, idx: c_int, enabled: bool) {
assert!(self.is_table(idx));
// SAFETY: is_table has a precondition to validate idx
unsafe {
lua_setreadonly(self.state, idx, enabled as c_int);
}
}
/// Sets the metatable for the value idx to the table located on the top of the stack.
///
/// Sets the metatable for individual tables and userdata or sets the metatable for an entire type.
pub fn set_metatable(&self, idx: c_int) {
luau_stack_precondition!(self.check_index(idx));
unsafe {
lua_setmetatable(self.state, idx);
}
}
/// Returns true if the value at idx is a vector, false otherwise
pub fn is_vector(&self, idx: c_int) -> bool {
self.type_of(idx) == LuauType::LUA_TVECTOR
}
/// Pushes a vector to the Luau stack
pub fn push_vector(&self, x: f32, y: f32, z: f32, #[cfg(feature = "luau_vector4")] w: f32) {
luau_stack_precondition!(self.check_stack(1));
// SAFETY: stack size is validated by precondition
unsafe {
#[cfg(not(feature = "luau_vector4"))]
lua_pushvector(self.state, x, y, z);
#[cfg(feature = "luau_vector4")]
lua_pushvector(self.state, x, y, z, w);
}
}
#[cfg(not(feature = "luau_vector4"))]
/// Returns the value of a vector if the value at idx is a vector or will return None
pub fn to_vector(&self, idx: c_int) -> Option<(f32, f32, f32)> {
luau_stack_precondition!(self.check_index(idx));
unsafe {
Option::from(lua_tovector(self.state, idx)).map(|ptr| (*ptr, *ptr.add(1), *ptr.add(2)))
}
}
#[cfg(feature = "luau_vector4")]
/// Returns the value of a vector if the value at idx is a vector or will return None
pub fn to_vector(&self, idx: c_int) -> Option<(f32, f32, f32, f32)> {
luau_stack_precondition!(self.check_index(idx));
unsafe {
Option::from(lua_tovector(self.state, idx))
.map(|ptr| (*ptr, *ptr.add(1), *ptr.add(2), *ptr.add(3)))
}
}
/// Returns true if the value at `idx` is a thread, false otherwise
pub fn is_thread(&self, idx: c_int) -> bool {
self.type_of(idx) == LuauType::LUA_TTHREAD
}
pub fn new_thread(&self) -> LuauThread {
unsafe {
let thread_ptr = lua_newthread(self.state);
LuauThread::from_ptr(thread_ptr, self.get_associated().main_thread_rc.clone())
}
}
pub fn get_thread(&self, idx: c_int) -> Option<LuauThread> {
let ptr = unsafe { lua_tothread(self.state, idx) };
if !ptr.is_null() {
unsafe {
Some(LuauThread::from_ptr(
ptr,
self.get_associated().main_thread_rc.clone(),
))
}
} else {
None
}
}
/// Returns the thread local userdata
pub fn get_thread_data<T: Any>(&self) -> Option<&T> {
let boxed = unsafe { (lua_getthreaddata(self.state) as *const Box<dyn Any>).as_ref()? };
boxed.downcast_ref()
}
/// Sets the thread local userdata
pub fn set_thread_data<T: Any>(&self, userdata: T) {
let b: Box<dyn Any> = Box::new(userdata);
unsafe {
lua_setthreaddata(self.state, Box::into_raw(b) as _);
}
}
/// Resumes the given Luau thread with the number of arguments.
///
/// Will resume the function on the top of the given Luau thread's execution stack
pub fn resume(&self, luau_thread: &LuauThread, nargs: c_int) -> LuauStatus {
unsafe { lua_resume(luau_thread.get_state().state, self.state, nargs) }
}
/// Returns true if the value at `idx` is a function, false otherwise
pub fn is_function(&self, idx: c_int) -> bool {
self.type_of(idx) == LuauType::LUA_TFUNCTION
}
/// Pushes a raw rust function to the stack which receives a pointer to the luau state and returns the number of result values
///
/// Can receive a number of upvalues specified by the `num_upvalues` argument which are accessed through ffi's upvalueindex
///
/// # Safety
/// You will need to uphold all safety invariants with respect to the Luau VM in the user supplied `func`
pub unsafe fn push_raw_function(
&self,
func: CFunction,
debug_name: Option<&CStr>,
num_upvals: c_int,
continuation: Option<LuaContinuation>,
) {
luau_stack_precondition!(self.check_stack(1));
assert!(
self.top() >= num_upvals,
"The number of upvalues for a raw function must not exceed the stack length"
);
// SAFETY: upvalue count and stack size are validated as a precondition and assert
unsafe {
lua_pushcclosurek(
self.state,
func,
if let Some(name) = debug_name {
name.as_ptr()
} else {
null()
},
num_upvals,
continuation,
);
}
}
/// Pushes a Rust function into Luau with an associated continuation
///
/// This function wraps a Rust function to allow closures to capture values, to avoid this minor overhead you can use `push_function_raw`
pub fn push_function_continuation<
F: FnMut(&Luau) -> c_int,
Cont: FnMut(&Luau, LuauStatus) -> c_int,
>(
&self,
func: F,
debug_name: Option<&CStr>,
num_upvals: c_int,
cont: Cont,
) {
assert!(
self.top() >= num_upvals,
"The number of upvalues for a raw function must not exceed the stack length"
);
luau_stack_precondition!(self.check_stack(2));
struct CallState<F, Cont> {
func: F,
cont: Cont,
}
let call_state = Box::new(CallState { func, cont });
unsafe extern "C-unwind" fn invoke_fn<
F: FnMut(&Luau) -> c_int,
Cont: FnMut(&Luau, LuauStatus) -> c_int,
>(
state: *mut _LuaState,
) -> c_int {
let call_state =
lua_tolightuserdata(state, lua_upvalueindex(1)).cast::<CallState<F, Cont>>();
let luau = Luau::from_ptr(state);
((*call_state).func)(&luau)
}
unsafe extern "C-unwind" fn invoke_continuation<
F: FnMut(&Luau) -> c_int,
Cont: FnMut(&Luau, LuauStatus) -> c_int,
>(
state: *mut _LuaState,
status: c_int,
) -> c_int {
let call_state =
lua_tolightuserdata(state, lua_upvalueindex(1)).cast::<CallState<F, Cont>>();
let luau = Luau::from_ptr(state);
((*call_state).cont)(&luau, std::mem::transmute::<c_int, LuauStatus>(status))
}
unsafe {
lua_pushlightuserdata(self.state, Box::into_raw(call_state) as _);
self.push_raw_function(
invoke_fn::<F, Cont>,
debug_name,
1 + num_upvals,
Some(invoke_continuation::<F, Cont>),
);
}
}
/// Pushes a Rust function into Luau
///
/// This function wraps a Rust function to allow closures to capture values, to avoid this minor overhead you can use `push_function_raw`
pub fn push_function<F: FnMut(&Luau) -> i32>(
&self,
func: F,
debug_name: Option<&CStr>,
num_upvals: c_int,
) {
assert!(
self.top() >= num_upvals,
"The number of upvalues for a raw function must not exceed the stack length"
);
luau_stack_precondition!(self.check_stack(2));
let func_box = Box::new(func);
unsafe extern "C-unwind" fn invoke_fn<T: FnMut(&Luau) -> i32>(
state: *mut _LuaState,
) -> c_int {
let func = lua_tolightuserdata(state, lua_upvalueindex(1)).cast::<T>();
let state = Luau::from_ptr(state);
(*func)(&state)
}
unsafe {
lua_pushlightuserdata(self.state, Box::into_raw(func_box) as _);
self.push_raw_function(invoke_fn::<F>, debug_name, 1 + num_upvals, None);
}
}
/// Calls the Luau function at the top of the stack returning the status of the Luau state when it returns
pub fn call(&self, nargs: c_int, nresults: c_int) -> LuauStatus {
assert!(
self.is_function(-1),
"The value at top of stack must be a function"
);
assert!(
self.top() >= nargs,
"Argument count may not exceed the total stack size"
);
luau_stack_precondition!(self.check_stack(nresults));
unsafe { lua_pcall(self.state, nargs, nresults, 0) }
}
/// Loads bytecode into the VM and pushes a function to the stack
pub fn load(&self, chunk_name: Option<&CStr>, bytecode: &[u8], env: c_int) -> Result<(), &str> {
// specifically allow env 0
luau_stack_precondition!(env == 0 || self.check_index(env));
luau_stack_precondition!(self.check_stack(2));
let success = unsafe {
luau_load(
self.state,
chunk_name.unwrap_or(c"").as_ptr(),
bytecode.as_ptr() as _,
bytecode.len(),
env,
)
};
if success == 0 {
Ok(())
} else {
dbg!(self.top());
// we have an error and know its ascii
Err(self.to_str(-1).unwrap().unwrap())
}
}
#[cfg(feature = "codegen")]
/// Compiles a function with native code generation.
///
/// This will fail silently if the codegen is not supported and initialized
pub fn codegen(&self, idx: c_int) {
luau_stack_precondition!(self.check_index(idx));
assert!(
self.is_function(idx),
"The value at idx must be a function to be compiled with codegen"
);
unsafe {
luau_codegen_compile(self.state, idx);
}
}
}
// TODO: do this
unsafe extern "C-unwind" fn fatal_runtime_error_handler(state: *mut _LuaState) -> c_int {
let luau = unsafe { Luau::from_ptr(state) };
panic!(
"Uncaught runtime error - \"{}\"",
String::from_utf8_lossy(luau.convert_to_str_slice(-1))
);
}
/// Final resting place for Luau code, we don't return from this.
unsafe extern "C-unwind" fn fatal_error_handler(state: *mut _LuaState, status: LuauStatus) {
match status {
// Unhandled runtime error
LuauStatus::LUA_ERRRUN => fatal_runtime_error_handler(state),
// memory allocation error, just die
LuauStatus::LUA_ERRMEM => std::process::abort(),
// some error handling mechanism errored
LuauStatus::LUA_ERRERR => panic!("Error originating from error handling mechanism"),
// shouldnt be reachable
_ => unreachable!(),
};
panic!("Fatal error in Luau execution");
}
impl Default for Luau {
fn default() -> Self {
Self::new(DefaultLuauAllocator {})
}
}
impl Drop for Luau {
fn drop(&mut self) {
if !self.owned {
return;
}
unsafe {
let mut associated: *mut AssociatedData = null_mut();
lua_getallocf(self.state, &raw mut associated as _);
let associated_owned = Box::from_raw(associated);
// mark main thread dead
associated_owned.main_thread_rc.set(false);
lua_close(self.state);
_ = associated_owned
}
}
}
#[macro_export]
macro_rules! try_luau {
($state:ident, $block:block) => {{
$state.push_function(|$state| $block, Some(c"_try_lua"), 0);
$state.call(0, 0)
}};
}
#[cfg(test)]
#[allow(non_snake_case)]
mod tests {
use std::{
ffi::{c_int, c_void},
hint::black_box,
rc::Rc,
};
use crate::{
Luau, LuauAllocator, _LuaState,
compile::Compiler,
lua_error, lua_tonumber, lua_upvalueindex,
userdata::{UserdataBorrowError, UserdataRef},
LuauLibs, LuauStatus, LuauType,
};
#[test]
fn try_test() {
let luau = Luau::default();
let status = try_luau!(luau, {
luau.push_boolean(true);
luau.error()
});
assert!(
matches!(status, LuauStatus::LUA_ERRRUN),
"Expected a runtime error"
);
assert!(luau.to_boolean(-1), "Expected the boolean to be true");
}
#[test]
#[should_panic]
fn stack_checking_no_value() {
let luau = Luau::default();
luau.is_number(1);
}
#[test]
#[should_panic]
fn stack_checking_neg_no_value() {
let luau = Luau::default();
luau.is_number(-1);
}
#[test]
fn stack_checking_has_value() {
let luau = Luau::default();
luau.push_number(0.0);
luau.is_number(-1);
luau.is_number(1);
}
#[cfg(all(feature = "codegen", feature = "compiler"))]
#[test]
fn codegen() {
use crate::compile::Compiler;
let compiler = Compiler::new();
let luau = Luau::default();
let result = compiler.compile("(function() return 123 end)()");
assert!(result.is_ok(), "Compiler result is expected to be OK");
let load_result = luau.load(None, result.bytecode().unwrap(), 0);
assert!(load_result.is_ok(), "Load result should be Ok");
let load_result = luau.load(Some(c"test"), result.bytecode().unwrap(), 0);
assert!(load_result.is_ok(), "Load result should be Ok");
luau.codegen(-1);
luau.call(0, 0);
}
#[test]
fn load_error() {
let luau = Luau::default();
let load_result = luau.load(None, b"\0Error!", 0);
// might change depending on luau updates
assert!(
load_result.is_err_and(|v| v == r#"[string ""]Error!"#),
"Expected load result to be an error and be the correct error message."
);
}
#[test]
fn load_libs() {
let luau = Luau::default();
luau.load_libs(LuauLibs::ALL_LIBS);
luau.get_field(luau.globals(), "table");
assert_eq!(luau.type_of(-1), LuauType::LUA_TTABLE);
luau.get_field(luau.globals(), "print");
assert_eq!(luau.type_of(-1), LuauType::LUA_TFUNCTION);
}
#[test]
fn tables() {
let luau = Luau::default();
luau.create_table();
luau.push_number(123.0);
luau.set_field(-2, "abc");
luau.get_field(-1, "abc");
assert_eq!(luau.to_number(-1), Some(123.0));
luau.pop(1);
// should be valid
luau.set_field(-1, "a");
}
#[test]
fn metatables() {
let luau = Luau::default();
luau.create_table();
luau.create_table();
let mut called: Option<String> = None;
luau.push_function(
|luau| {
called = luau.to_str(-1).map(Result::unwrap).map(str::to_string);
0
},
None,
0,
);
luau.set_field(-2, "__index");
luau.set_metatable(-2);
let index = "Hello!".to_string();
luau.get_field(-1, &index);
assert_eq!(called, Some(index));
}
#[test]
#[should_panic]
fn unhandled_error() {
let luau = Luau::default();
luau.push_string("hello error!");
unsafe {
lua_error(luau.to_ptr());
}
}
#[test]
fn pop() {
let luau = Luau::default();
luau.push_number(0.0);
assert_eq!(luau.top(), 1);
luau.pop(1);
assert_eq!(luau.top(), 0);
luau.push_number(0.0);
luau.push_number(0.0);
assert_eq!(luau.top(), 2);
luau.pop(2);
assert_eq!(luau.top(), 0);
}
#[test]
fn threads() {
let luau = Luau::default();
let thread = luau.new_thread();
let thread_state = thread.get_state();
let mut was_called = false;
thread_state.push_function(
|_| {
was_called = true;
0
},
None,
0,
);
luau.resume(&thread, 0);
assert!(was_called, "Expected thread function to be called");
}
#[test]
fn app_data() {
let luau = Luau::default();
luau.set_app_data(Some(true));
assert_eq!(luau.get_app_data::<bool>().copied(), Some(true))
}
#[test]
fn function_upvalue_test() {
let luau = Luau::default();
luau.push_number(1.0);
luau.push_number(2.0);
luau.push_number(3.0);
luau.push_function(
|luau| {
assert_eq!(luau.to_number(luau.upvalue(1)), Some(1.0));
assert_eq!(luau.to_number(luau.upvalue(2)), Some(2.0));
assert_eq!(luau.to_number(luau.upvalue(3)), Some(3.0));
0
},
Some(c"test"),
3,
);
luau.call(0, 0);
}
#[test]
fn raw_function_upvalue_test() {
let luau = Luau::default();
luau.push_number(1.0);
luau.push_number(2.0);
luau.push_number(3.0);
unsafe extern "C-unwind" fn test_extern_fn(state: *mut _LuaState) -> c_int {
assert_eq!(lua_tonumber(state, lua_upvalueindex(1)), 1.0);
assert_eq!(lua_tonumber(state, lua_upvalueindex(2)), 2.0);
assert_eq!(lua_tonumber(state, lua_upvalueindex(3)), 3.0);
0
}
unsafe {
luau.push_raw_function(test_extern_fn, Some(c"test"), 3, None);
}
luau.call(0, 0);
}
#[test]
fn continuations() {
let luau = Luau::default();
let compiler = Compiler::new();
let bc = compiler.compile("(...)()");
let thread = luau.new_thread();
let thread_state = thread.get_state();
let mut cont = false;
thread_state.push_function_continuation(
|l| l.yield_luau(0),
None,
0,
|_, _| {
cont = true;
0
},
);
thread_state.load(None, bc.bytecode().unwrap(), 0).unwrap();
luau.resume(&thread, 1);
luau.resume(&thread, 0);
assert!(cont, "Expected that the continuation would be called.")
}
#[test]
#[should_panic]
fn luau_panic_unwind() {
struct PanicAllocator;
impl LuauAllocator for PanicAllocator {
fn allocate(&self, _: usize) -> *mut std::ffi::c_void {
panic!()
}
fn reallocate(&self, _: *mut c_void, _: usize, _: usize) -> *mut std::ffi::c_void {
panic!()
}
fn deallocate(&self, _: *mut c_void, _: usize) {
panic!()
}
}
{
black_box(Luau::new(PanicAllocator {}));
};
}
#[test]
fn function_check() {
let luau = Luau::default();
luau.push_function(
|l| {
l.check_args(1, None);
0
},
None,
0,
);
let status = luau.call(0, 0);
assert!(
matches!(status, LuauStatus::LUA_ERRRUN),
"Expected there to be a runtime error."
);
luau.push_function(
|l| {
l.check_args(1, None);
0
},
Some(c"test"),
0,
);
let status = luau.call(0, 0);
assert!(
matches!(status, LuauStatus::LUA_ERRRUN),
"Expected there to be a runtime error."
);
}
#[test]
fn userdata_borrow() {
let luau = Luau::default();
luau.push_userdata(());
{
let borrow = luau.try_borrow_userdata_mut::<()>(-1);
assert!(
borrow.as_ref().is_some_and(Result::is_ok),
"Expected mutable borrow for userdata to be valid"
);
assert!(
matches!(
luau.try_borrow_userdata::<()>(-1),
Some(Err(UserdataBorrowError::AlreadyMutable))
),
"Expected immutable borrow for userdata to be invalid"
);
assert!(
matches!(
luau.try_borrow_userdata_mut::<()>(-1),
Some(Err(UserdataBorrowError::AlreadyMutable))
),
"Expected mutable borrow for userdata to be invalid"
);
drop(borrow);
assert!(
matches!(luau.try_borrow_userdata_mut::<()>(-1), Some(Ok(_))),
"Expected mutable borrow for userdata to be valid"
);
}
{
let borrow = luau.try_borrow_userdata::<()>(-1);
assert!(
matches!(borrow, Some(Ok(_))),
"Expected to be a valid borrow"
);
assert!(
matches!(
luau.try_borrow_userdata_mut::<()>(-1),
Some(Err(UserdataBorrowError::AlreadyImmutable))
),
"Expected borrow to be an AlreadyImmutable error"
);
}
}
#[test]
fn userdata_values() {
let luau = Luau::default();
luau.push_userdata(());
let mut vec = Vec::with_capacity(128);
for i in 0..128 {
vec.push(i);
}
luau.push_userdata(vec);
#[repr(transparent)]
struct DropCheck(Rc<bool>);
let drop_rc = Rc::new(true);
let yes_drop = DropCheck(drop_rc.clone());
luau.push_userdata(yes_drop);
assert!(luau.borrow_userdata(-3).is_some_and(
#[allow(clippy::unit_cmp)]
|v: UserdataRef<()>| *v == ()
));
assert!(luau
.borrow_userdata::<Vec<i32>>(-2)
.is_some_and(|v| v.is_sorted())); // is larger data preserved correctly
assert!(luau.borrow_userdata::<DropCheck>(-1).is_some());
drop(luau);
// assert!(, "Expected userdata to be dropped with luau state");
}
#[test]
fn string_values() {
let luau = Luau::default();
const TEST_CONST: &[u8] = &[0xCA, 0xFE, 0xBA, 0xBE];
const INVALID_SEQUENCE: &[u8] = &[0xC3, 0x28];
luau.push_string("Hello, world!");
luau.push_string(TEST_CONST);
luau.push_number(12345.0f64);
luau.push_string(INVALID_SEQUENCE);
assert_eq!(luau.to_str_slice(-4), Some(b"Hello, world!" as _));
assert_eq!(luau.to_str(-4), Some(Ok("Hello, world!")));
assert_eq!(luau.to_str_slice(1), Some(b"Hello, world!" as _));
assert_eq!(luau.to_str(1), Some(Ok("Hello, world!")));
assert_eq!(luau.to_str_slice(-3), Some(TEST_CONST));
assert_eq!(luau.to_str_slice(2), Some(TEST_CONST));
assert_eq!(luau.to_str_slice(-2), Some(b"12345" as _));
assert_eq!(luau.to_str(-2), Some(Ok("12345")));
assert_eq!(luau.to_str_slice(3), Some(b"12345" as _));
assert_eq!(luau.to_str(3), Some(Ok("12345")));
assert_eq!(luau.to_str_slice(-1), Some(INVALID_SEQUENCE));
assert!(luau.to_str(-1).is_some_and(|r| r.is_err()));
assert_eq!(luau.to_str_slice(4), Some(INVALID_SEQUENCE));
assert!(luau.to_str(4).is_some_and(|r| r.is_err()));
}
#[test]
fn numeric_values() {
let luau = Luau::default();
luau.push_number(f64::NAN);
luau.push_number(f64::INFINITY);
luau.push_number(f64::EPSILON);
luau.push_string("12345");
// nan is not equal to itself, because that makes sense
assert_eq!(
luau.to_number(-4).map(f64::to_bits),
Some(f64::NAN.to_bits())
);
assert_eq!(
luau.to_number(1).map(f64::to_bits),
Some(f64::NAN.to_bits())
);
assert_eq!(luau.to_number(-3), Some(f64::INFINITY));
assert_eq!(luau.to_number(2), Some(f64::INFINITY));
assert_eq!(luau.to_number(-2), Some(f64::EPSILON));
assert_eq!(luau.to_number(3), Some(f64::EPSILON));
assert_eq!(luau.to_number(-1), Some(12345.0f64));
assert_eq!(luau.to_number(4), Some(12345.0f64));
}
}