luau-src 0.3.0

Luau source code bindings
Documentation
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
// This file is part of the Luau programming language and is licensed under MIT License; see LICENSE.txt for details
// This code is based on Lua 5.x implementation licensed under MIT License; see lua_LICENSE.txt for details
#include "lapi.h"

#include "lstate.h"
#include "lstring.h"
#include "ltable.h"
#include "lfunc.h"
#include "lgc.h"
#include "ldo.h"
#include "ludata.h"
#include "lvm.h"
#include "lnumutils.h"

#include <string.h>

LUAU_FASTFLAG(LuauActivateBeforeExec)

const char* lua_ident = "$Lua: Lua 5.1.4 Copyright (C) 1994-2008 Lua.org, PUC-Rio $\n"
                        "$Authors: R. Ierusalimschy, L. H. de Figueiredo & W. Celes $\n"
                        "$URL: www.lua.org $\n";

const char* luau_ident = "$Luau: Copyright (C) 2019-2021 Roblox Corporation $\n"
                         "$URL: luau-lang.org $\n";

#define api_checknelems(L, n) api_check(L, (n) <= (L->top - L->base))


#define api_checkvalidindex(L, i) api_check(L, (i) != luaO_nilobject)


#define api_incr_top(L) \

    { \
        api_check(L, L->top < L->ci->top); \
        L->top++; \
    }

static Table* getcurrenv(lua_State* L)
{
    if (L->ci == L->base_ci)  /* no enclosing function? */
        return hvalue(gt(L)); /* use global table as environment */
    else
    {
        Closure* func = curr_func(L);
        return func->env;
    }
}

static LUAU_NOINLINE TValue* pseudo2addr(lua_State* L, int idx)
{
    api_check(L, lua_ispseudo(idx));
    switch (idx)
    { /* pseudo-indices */
    case LUA_REGISTRYINDEX:
        return registry(L);
    case LUA_ENVIRONINDEX:
    {
        sethvalue(L, &L->env, getcurrenv(L));
        return &L->env;
    }
    case LUA_GLOBALSINDEX:
        return gt(L);
    default:
    {
        Closure* func = curr_func(L);
        idx = LUA_GLOBALSINDEX - idx;
        return (idx <= func->nupvalues) ? &func->c.upvals[idx - 1] : cast_to(TValue*, luaO_nilobject);
    }
    }
}

static LUAU_FORCEINLINE TValue* index2addr(lua_State* L, int idx)
{
    if (idx > 0)
    {
        TValue* o = L->base + (idx - 1);
        api_check(L, idx <= L->ci->top - L->base);
        if (o >= L->top)
            return cast_to(TValue*, luaO_nilobject);
        else
            return o;
    }
    else if (idx > LUA_REGISTRYINDEX)
    {
        api_check(L, idx != 0 && -idx <= L->top - L->base);
        return L->top + idx;
    }
    else
    {
        return pseudo2addr(L, idx);
    }
}

const TValue* luaA_toobject(lua_State* L, int idx)
{
    StkId p = index2addr(L, idx);
    return (p == luaO_nilobject) ? NULL : p;
}

void luaA_pushobject(lua_State* L, const TValue* o)
{
    setobj2s(L, L->top, o);
    api_incr_top(L);
}

int lua_checkstack(lua_State* L, int size)
{
    int res = 1;
    if (size > LUAI_MAXCSTACK || (L->top - L->base + size) > LUAI_MAXCSTACK)
        res = 0; /* stack overflow */
    else if (size > 0)
    {
        luaD_checkstack(L, size);
        expandstacklimit(L, L->top + size);
    }
    return res;
}

void lua_rawcheckstack(lua_State* L, int size)
{
    luaD_checkstack(L, size);
    expandstacklimit(L, L->top + size);
    return;
}

void lua_xmove(lua_State* from, lua_State* to, int n)
{
    if (from == to)
        return;
    api_checknelems(from, n);
    api_check(from, from->global == to->global);
    api_check(from, to->ci->top - to->top >= n);
    luaC_checkthreadsleep(to);

    StkId ttop = to->top;
    StkId ftop = from->top - n;
    for (int i = 0; i < n; i++)
        setobj2s(to, ttop + i, ftop + i);

    from->top = ftop;
    to->top = ttop + n;

    return;
}

void lua_xpush(lua_State* from, lua_State* to, int idx)
{
    api_check(from, from->global == to->global);
    luaC_checkthreadsleep(to);
    setobj2s(to, to->top, index2addr(from, idx));
    api_incr_top(to);
    return;
}

lua_State* lua_newthread(lua_State* L)
{
    luaC_checkGC(L);
    luaC_checkthreadsleep(L);
    lua_State* L1 = luaE_newthread(L);
    setthvalue(L, L->top, L1);
    api_incr_top(L);
    global_State* g = L->global;
    if (g->cb.userthread)
        g->cb.userthread(L, L1);
    return L1;
}

lua_State* lua_mainthread(lua_State* L)
{
    return L->global->mainthread;
}

/*
** basic stack manipulation
*/

int lua_absindex(lua_State* L, int idx)
{
    api_check(L, (idx > 0 && idx <= L->top - L->base) || (idx < 0 && -idx <= L->top - L->base) || lua_ispseudo(idx));
    return idx > 0 || lua_ispseudo(idx) ? idx : cast_int(L->top - L->base) + idx + 1;
}

int lua_gettop(lua_State* L)
{
    return cast_int(L->top - L->base);
}

void lua_settop(lua_State* L, int idx)
{
    if (idx >= 0)
    {
        api_check(L, idx <= L->stack_last - L->base);
        while (L->top < L->base + idx)
            setnilvalue(L->top++);
        L->top = L->base + idx;
    }
    else
    {
        api_check(L, -(idx + 1) <= (L->top - L->base));
        L->top += idx + 1; /* `subtract' index (index is negative) */
    }
    return;
}

void lua_remove(lua_State* L, int idx)
{
    StkId p = index2addr(L, idx);
    api_checkvalidindex(L, p);
    while (++p < L->top)
        setobjs2s(L, p - 1, p);
    L->top--;
    return;
}

void lua_insert(lua_State* L, int idx)
{
    luaC_checkthreadsleep(L);
    StkId p = index2addr(L, idx);
    api_checkvalidindex(L, p);
    for (StkId q = L->top; q > p; q--)
        setobjs2s(L, q, q - 1);
    setobjs2s(L, p, L->top);
    return;
}

void lua_replace(lua_State* L, int idx)
{
    /* explicit test for incompatible code */
    if (idx == LUA_ENVIRONINDEX && L->ci == L->base_ci)
        luaG_runerror(L, "no calling environment");
    api_checknelems(L, 1);
    luaC_checkthreadsleep(L);
    StkId o = index2addr(L, idx);
    api_checkvalidindex(L, o);
    if (idx == LUA_ENVIRONINDEX)
    {
        Closure* func = curr_func(L);
        api_check(L, ttistable(L->top - 1));
        func->env = hvalue(L->top - 1);
        luaC_barrier(L, func, L->top - 1);
    }
    else
    {
        setobj(L, o, L->top - 1);
        if (idx < LUA_GLOBALSINDEX) /* function upvalue? */
            luaC_barrier(L, curr_func(L), L->top - 1);
    }
    L->top--;
    return;
}

void lua_pushvalue(lua_State* L, int idx)
{
    luaC_checkthreadsleep(L);
    StkId o = index2addr(L, idx);
    setobj2s(L, L->top, o);
    api_incr_top(L);
    return;
}

/*
** access functions (stack -> C)
*/

int lua_type(lua_State* L, int idx)
{
    StkId o = index2addr(L, idx);
    return (o == luaO_nilobject) ? LUA_TNONE : ttype(o);
}

const char* lua_typename(lua_State* L, int t)
{
    return (t == LUA_TNONE) ? "no value" : luaT_typenames[t];
}

int lua_iscfunction(lua_State* L, int idx)
{
    StkId o = index2addr(L, idx);
    return iscfunction(o);
}

int lua_isLfunction(lua_State* L, int idx)
{
    StkId o = index2addr(L, idx);
    return isLfunction(o);
}

int lua_isnumber(lua_State* L, int idx)
{
    TValue n;
    const TValue* o = index2addr(L, idx);
    return tonumber(o, &n);
}

int lua_isstring(lua_State* L, int idx)
{
    int t = lua_type(L, idx);
    return (t == LUA_TSTRING || t == LUA_TNUMBER);
}

int lua_isuserdata(lua_State* L, int idx)
{
    const TValue* o = index2addr(L, idx);
    return (ttisuserdata(o) || ttislightuserdata(o));
}

int lua_rawequal(lua_State* L, int index1, int index2)
{
    StkId o1 = index2addr(L, index1);
    StkId o2 = index2addr(L, index2);
    return (o1 == luaO_nilobject || o2 == luaO_nilobject) ? 0 : luaO_rawequalObj(o1, o2);
}

int lua_equal(lua_State* L, int index1, int index2)
{
    StkId o1, o2;
    int i;
    o1 = index2addr(L, index1);
    o2 = index2addr(L, index2);
    i = (o1 == luaO_nilobject || o2 == luaO_nilobject) ? 0 : equalobj(L, o1, o2);
    return i;
}

int lua_lessthan(lua_State* L, int index1, int index2)
{
    StkId o1, o2;
    int i;
    o1 = index2addr(L, index1);
    o2 = index2addr(L, index2);
    i = (o1 == luaO_nilobject || o2 == luaO_nilobject) ? 0 : luaV_lessthan(L, o1, o2);
    return i;
}

double lua_tonumberx(lua_State* L, int idx, int* isnum)
{
    TValue n;
    const TValue* o = index2addr(L, idx);
    if (tonumber(o, &n))
    {
        if (isnum)
            *isnum = 1;
        return nvalue(o);
    }
    else
    {
        if (isnum)
            *isnum = 0;
        return 0;
    }
}

int lua_tointegerx(lua_State* L, int idx, int* isnum)
{
    TValue n;
    const TValue* o = index2addr(L, idx);
    if (tonumber(o, &n))
    {
        int res;
        double num = nvalue(o);
        luai_num2int(res, num);
        if (isnum)
            *isnum = 1;
        return res;
    }
    else
    {
        if (isnum)
            *isnum = 0;
        return 0;
    }
}

unsigned lua_tounsignedx(lua_State* L, int idx, int* isnum)
{
    TValue n;
    const TValue* o = index2addr(L, idx);
    if (tonumber(o, &n))
    {
        unsigned res;
        double num = nvalue(o);
        luai_num2unsigned(res, num);
        if (isnum)
            *isnum = 1;
        return res;
    }
    else
    {
        if (isnum)
            *isnum = 0;
        return 0;
    }
}

int lua_toboolean(lua_State* L, int idx)
{
    const TValue* o = index2addr(L, idx);
    return !l_isfalse(o);
}

const char* lua_tolstring(lua_State* L, int idx, size_t* len)
{
    StkId o = index2addr(L, idx);
    if (!ttisstring(o))
    {
        luaC_checkthreadsleep(L);
        if (!luaV_tostring(L, o))
        { /* conversion failed? */
            if (len != NULL)
                *len = 0;
            return NULL;
        }
        luaC_checkGC(L);
        o = index2addr(L, idx); /* previous call may reallocate the stack */
    }
    if (len != NULL)
        *len = tsvalue(o)->len;
    return svalue(o);
}

const char* lua_tostringatom(lua_State* L, int idx, int* atom)
{
    StkId o = index2addr(L, idx);
    if (!ttisstring(o))
        return NULL;
    const TString* s = tsvalue(o);
    if (atom)
        *atom = s->atom;
    return getstr(s);
}

const char* lua_namecallatom(lua_State* L, int* atom)
{
    const TString* s = L->namecall;
    if (!s)
        return NULL;
    if (atom)
        *atom = s->atom;
    return getstr(s);
}

const float* lua_tovector(lua_State* L, int idx)
{
    StkId o = index2addr(L, idx);
    if (!ttisvector(o))
    {
        return NULL;
    }
    return vvalue(o);
}

int lua_objlen(lua_State* L, int idx)
{
    StkId o = index2addr(L, idx);
    switch (ttype(o))
    {
    case LUA_TSTRING:
        return tsvalue(o)->len;
    case LUA_TUSERDATA:
        return uvalue(o)->len;
    case LUA_TTABLE:
        return luaH_getn(hvalue(o));
    case LUA_TNUMBER:
    {
        int l = (luaV_tostring(L, o) ? tsvalue(o)->len : 0);
        return l;
    }
    default:
        return 0;
    }
}

lua_CFunction lua_tocfunction(lua_State* L, int idx)
{
    StkId o = index2addr(L, idx);
    return (!iscfunction(o)) ? NULL : cast_to(lua_CFunction, clvalue(o)->c.f);
}

void* lua_touserdata(lua_State* L, int idx)
{
    StkId o = index2addr(L, idx);
    switch (ttype(o))
    {
    case LUA_TUSERDATA:
        return uvalue(o)->data;
    case LUA_TLIGHTUSERDATA:
        return pvalue(o);
    default:
        return NULL;
    }
}

void* lua_touserdatatagged(lua_State* L, int idx, int tag)
{
    StkId o = index2addr(L, idx);
    return (ttisuserdata(o) && uvalue(o)->tag == tag) ? uvalue(o)->data : NULL;
}

int lua_userdatatag(lua_State* L, int idx)
{
    StkId o = index2addr(L, idx);
    if (ttisuserdata(o))
        return uvalue(o)->tag;
    return -1;
}

lua_State* lua_tothread(lua_State* L, int idx)
{
    StkId o = index2addr(L, idx);
    return (!ttisthread(o)) ? NULL : thvalue(o);
}

const void* lua_topointer(lua_State* L, int idx)
{
    StkId o = index2addr(L, idx);
    switch (ttype(o))
    {
    case LUA_TTABLE:
        return hvalue(o);
    case LUA_TFUNCTION:
        return clvalue(o);
    case LUA_TTHREAD:
        return thvalue(o);
    case LUA_TUSERDATA:
    case LUA_TLIGHTUSERDATA:
        return lua_touserdata(L, idx);
    default:
        return NULL;
    }
}

/*
** push functions (C -> stack)
*/

void lua_pushnil(lua_State* L)
{
    setnilvalue(L->top);
    api_incr_top(L);
    return;
}

void lua_pushnumber(lua_State* L, double n)
{
    setnvalue(L->top, n);
    api_incr_top(L);
    return;
}

void lua_pushinteger(lua_State* L, int n)
{
    setnvalue(L->top, cast_num(n));
    api_incr_top(L);
    return;
}

void lua_pushunsigned(lua_State* L, unsigned u)
{
    setnvalue(L->top, cast_num(u));
    api_incr_top(L);
    return;
}

#if LUA_VECTOR_SIZE == 4
void lua_pushvector(lua_State* L, float x, float y, float z, float w)
{
    setvvalue(L->top, x, y, z, w);
    api_incr_top(L);
    return;
}
#else
void lua_pushvector(lua_State* L, float x, float y, float z)
{
    setvvalue(L->top, x, y, z, 0.0f);
    api_incr_top(L);
    return;
}
#endif

void lua_pushlstring(lua_State* L, const char* s, size_t len)
{
    luaC_checkGC(L);
    luaC_checkthreadsleep(L);
    setsvalue2s(L, L->top, luaS_newlstr(L, s, len));
    api_incr_top(L);
    return;
}

void lua_pushstring(lua_State* L, const char* s)
{
    if (s == NULL)
        lua_pushnil(L);
    else
        lua_pushlstring(L, s, strlen(s));
}

const char* lua_pushvfstring(lua_State* L, const char* fmt, va_list argp)
{
    luaC_checkGC(L);
    luaC_checkthreadsleep(L);
    const char* ret = luaO_pushvfstring(L, fmt, argp);
    return ret;
}

const char* lua_pushfstringL(lua_State* L, const char* fmt, ...)
{
    luaC_checkGC(L);
    luaC_checkthreadsleep(L);
    va_list argp;
    va_start(argp, fmt);
    const char* ret = luaO_pushvfstring(L, fmt, argp);
    va_end(argp);
    return ret;
}

void lua_pushcclosurek(lua_State* L, lua_CFunction fn, const char* debugname, int nup, lua_Continuation cont)
{
    luaC_checkGC(L);
    luaC_checkthreadsleep(L);
    api_checknelems(L, nup);
    Closure* cl = luaF_newCclosure(L, nup, getcurrenv(L));
    cl->c.f = fn;
    cl->c.cont = cont;
    cl->c.debugname = debugname;
    L->top -= nup;
    while (nup--)
        setobj2n(L, &cl->c.upvals[nup], L->top + nup);
    setclvalue(L, L->top, cl);
    LUAU_ASSERT(iswhite(obj2gco(cl)));
    api_incr_top(L);
    return;
}

void lua_pushboolean(lua_State* L, int b)
{
    setbvalue(L->top, (b != 0)); /* ensure that true is 1 */
    api_incr_top(L);
    return;
}

void lua_pushlightuserdata(lua_State* L, void* p)
{
    setpvalue(L->top, p);
    api_incr_top(L);
    return;
}

int lua_pushthread(lua_State* L)
{
    luaC_checkthreadsleep(L);
    setthvalue(L, L->top, L);
    api_incr_top(L);
    return L->global->mainthread == L;
}

/*
** get functions (Lua -> stack)
*/

void lua_gettable(lua_State* L, int idx)
{
    luaC_checkthreadsleep(L);
    StkId t = index2addr(L, idx);
    api_checkvalidindex(L, t);
    luaV_gettable(L, t, L->top - 1, L->top - 1);
    return;
}

void lua_getfield(lua_State* L, int idx, const char* k)
{
    luaC_checkthreadsleep(L);
    StkId t = index2addr(L, idx);
    api_checkvalidindex(L, t);
    TValue key;
    setsvalue(L, &key, luaS_new(L, k));
    luaV_gettable(L, t, &key, L->top);
    api_incr_top(L);
    return;
}

void lua_rawgetfield(lua_State* L, int idx, const char* k)
{
    luaC_checkthreadsleep(L);
    StkId t = index2addr(L, idx);
    api_check(L, ttistable(t));
    TValue key;
    setsvalue(L, &key, luaS_new(L, k));
    setobj2s(L, L->top, luaH_getstr(hvalue(t), tsvalue(&key)));
    api_incr_top(L);
    return;
}

void lua_rawget(lua_State* L, int idx)
{
    luaC_checkthreadsleep(L);
    StkId t = index2addr(L, idx);
    api_check(L, ttistable(t));
    setobj2s(L, L->top - 1, luaH_get(hvalue(t), L->top - 1));
    return;
}

void lua_rawgeti(lua_State* L, int idx, int n)
{
    luaC_checkthreadsleep(L);
    StkId t = index2addr(L, idx);
    api_check(L, ttistable(t));
    setobj2s(L, L->top, luaH_getnum(hvalue(t), n));
    api_incr_top(L);
    return;
}

void lua_createtable(lua_State* L, int narray, int nrec)
{
    luaC_checkGC(L);
    luaC_checkthreadsleep(L);
    sethvalue(L, L->top, luaH_new(L, narray, nrec));
    api_incr_top(L);
    return;
}

void lua_setreadonly(lua_State* L, int objindex, int enabled)
{
    const TValue* o = index2addr(L, objindex);
    api_check(L, ttistable(o));
    Table* t = hvalue(o);
    api_check(L, t != hvalue(registry(L)));
    t->readonly = bool(enabled);
    return;
}

int lua_getreadonly(lua_State* L, int objindex)
{
    const TValue* o = index2addr(L, objindex);
    api_check(L, ttistable(o));
    Table* t = hvalue(o);
    int res = t->readonly;
    return res;
}

void lua_setsafeenv(lua_State* L, int objindex, int enabled)
{
    const TValue* o = index2addr(L, objindex);
    api_check(L, ttistable(o));
    Table* t = hvalue(o);
    t->safeenv = bool(enabled);
    return;
}

int lua_getmetatable(lua_State* L, int objindex)
{
    const TValue* obj;
    Table* mt = NULL;
    int res;
    obj = index2addr(L, objindex);
    switch (ttype(obj))
    {
    case LUA_TTABLE:
        mt = hvalue(obj)->metatable;
        break;
    case LUA_TUSERDATA:
        mt = uvalue(obj)->metatable;
        break;
    default:
        mt = L->global->mt[ttype(obj)];
        break;
    }
    if (mt == NULL)
        res = 0;
    else
    {
        sethvalue(L, L->top, mt);
        api_incr_top(L);
        res = 1;
    }
    return res;
}

void lua_getfenv(lua_State* L, int idx)
{
    StkId o;
    o = index2addr(L, idx);
    api_checkvalidindex(L, o);
    switch (ttype(o))
    {
    case LUA_TFUNCTION:
        sethvalue(L, L->top, clvalue(o)->env);
        break;
    case LUA_TTHREAD:
        setobj2s(L, L->top, gt(thvalue(o)));
        break;
    default:
        setnilvalue(L->top);
        break;
    }
    api_incr_top(L);
    return;
}

/*
** set functions (stack -> Lua)
*/

void lua_settable(lua_State* L, int idx)
{
    StkId t;
    api_checknelems(L, 2);
    t = index2addr(L, idx);
    api_checkvalidindex(L, t);
    luaV_settable(L, t, L->top - 2, L->top - 1);
    L->top -= 2; /* pop index and value */
    return;
}

void lua_setfield(lua_State* L, int idx, const char* k)
{
    StkId t;
    TValue key;
    api_checknelems(L, 1);
    t = index2addr(L, idx);
    api_checkvalidindex(L, t);
    setsvalue(L, &key, luaS_new(L, k));
    luaV_settable(L, t, &key, L->top - 1);
    L->top--; /* pop value */
    return;
}

void lua_rawset(lua_State* L, int idx)
{
    StkId t;
    api_checknelems(L, 2);
    t = index2addr(L, idx);
    api_check(L, ttistable(t));
    if (hvalue(t)->readonly)
        luaG_runerror(L, "Attempt to modify a readonly table");
    setobj2t(L, luaH_set(L, hvalue(t), L->top - 2), L->top - 1);
    luaC_barriert(L, hvalue(t), L->top - 1);
    L->top -= 2;
    return;
}

void lua_rawseti(lua_State* L, int idx, int n)
{
    StkId o;
    api_checknelems(L, 1);
    o = index2addr(L, idx);
    api_check(L, ttistable(o));
    if (hvalue(o)->readonly)
        luaG_runerror(L, "Attempt to modify a readonly table");
    setobj2t(L, luaH_setnum(L, hvalue(o), n), L->top - 1);
    luaC_barriert(L, hvalue(o), L->top - 1);
    L->top--;
    return;
}

int lua_setmetatable(lua_State* L, int objindex)
{
    TValue* obj;
    Table* mt;
    api_checknelems(L, 1);
    obj = index2addr(L, objindex);
    api_checkvalidindex(L, obj);
    if (ttisnil(L->top - 1))
        mt = NULL;
    else
    {
        api_check(L, ttistable(L->top - 1));
        mt = hvalue(L->top - 1);
    }
    switch (ttype(obj))
    {
    case LUA_TTABLE:
    {
        if (hvalue(obj)->readonly)
            luaG_runerror(L, "Attempt to modify a readonly table");
        hvalue(obj)->metatable = mt;
        if (mt)
            luaC_objbarriert(L, hvalue(obj), mt);
        break;
    }
    case LUA_TUSERDATA:
    {
        uvalue(obj)->metatable = mt;
        if (mt)
            luaC_objbarrier(L, uvalue(obj), mt);
        break;
    }
    default:
    {
        L->global->mt[ttype(obj)] = mt;
        break;
    }
    }
    L->top--;
    return 1;
}

int lua_setfenv(lua_State* L, int idx)
{
    StkId o;
    int res = 1;
    api_checknelems(L, 1);
    o = index2addr(L, idx);
    api_checkvalidindex(L, o);
    api_check(L, ttistable(L->top - 1));
    switch (ttype(o))
    {
    case LUA_TFUNCTION:
        clvalue(o)->env = hvalue(L->top - 1);
        break;
    case LUA_TTHREAD:
        sethvalue(L, gt(thvalue(o)), hvalue(L->top - 1));
        break;
    default:
        res = 0;
        break;
    }
    if (res)
    {
        luaC_objbarrier(L, &gcvalue(o)->gch, hvalue(L->top - 1));
    }
    L->top--;
    return res;
}

/*
** `load' and `call' functions (run Lua code)
*/

#define adjustresults(L, nres) \

    { \
        if (nres == LUA_MULTRET && L->top >= L->ci->top) \
            L->ci->top = L->top; \
    }

#define checkresults(L, na, nr) api_check(L, (nr) == LUA_MULTRET || (L->ci->top - L->top >= (nr) - (na)))


void lua_call(lua_State* L, int nargs, int nresults)
{
    StkId func;
    api_checknelems(L, nargs + 1);
    api_check(L, L->status == 0);
    checkresults(L, nargs, nresults);
    func = L->top - (nargs + 1);

    if (FFlag::LuauActivateBeforeExec)
    {
        luaD_call(L, func, nresults);
    }
    else
    {
        int oldactive = luaC_threadactive(L);
        l_setbit(L->stackstate, THREAD_ACTIVEBIT);
        luaC_checkthreadsleep(L);

        luaD_call(L, func, nresults);

        if (!oldactive)
            resetbit(L->stackstate, THREAD_ACTIVEBIT);
    }

    adjustresults(L, nresults);
    return;
}

/*
** Execute a protected call.
*/
struct CallS
{ /* data to `f_call' */
    StkId func;
    int nresults;
};

static void f_call(lua_State* L, void* ud)
{
    struct CallS* c = cast_to(struct CallS*, ud);
    luaD_call(L, c->func, c->nresults);
    return;
}

int lua_pcall(lua_State* L, int nargs, int nresults, int errfunc)
{
    struct CallS c;
    int status;
    ptrdiff_t func;
    api_checknelems(L, nargs + 1);
    api_check(L, L->status == 0);
    checkresults(L, nargs, nresults);
    if (errfunc == 0)
        func = 0;
    else
    {
        StkId o = index2addr(L, errfunc);
        api_checkvalidindex(L, o);
        func = savestack(L, o);
    }
    c.func = L->top - (nargs + 1); /* function to be called */
    c.nresults = nresults;

    if (FFlag::LuauActivateBeforeExec)
    {
        status = luaD_pcall(L, f_call, &c, savestack(L, c.func), func);
    }
    else
    {
        int oldactive = luaC_threadactive(L);
        l_setbit(L->stackstate, THREAD_ACTIVEBIT);
        luaC_checkthreadsleep(L);

        status = luaD_pcall(L, f_call, &c, savestack(L, c.func), func);

        if (!oldactive)
            resetbit(L->stackstate, THREAD_ACTIVEBIT);
    }

    adjustresults(L, nresults);
    return status;
}

int lua_status(lua_State* L)
{
    return L->status;
}

void* lua_getthreaddata(lua_State* L)
{
    return L->userdata;
}

void lua_setthreaddata(lua_State* L, void* data)
{
    L->userdata = data;
}

/*
** Garbage-collection function
*/

int lua_gc(lua_State* L, int what, int data)
{
    int res = 0;
    condhardmemtests(luaC_validate(L), 1);
    global_State* g = L->global;
    switch (what)
    {
    case LUA_GCSTOP:
    {
        g->GCthreshold = SIZE_MAX;
        break;
    }
    case LUA_GCRESTART:
    {
        g->GCthreshold = g->totalbytes;
        break;
    }
    case LUA_GCCOLLECT:
    {
        luaC_fullgc(L);
        break;
    }
    case LUA_GCCOUNT:
    {
        /* GC values are expressed in Kbytes: #bytes/2^10 */
        res = cast_int(g->totalbytes >> 10);
        break;
    }
    case LUA_GCCOUNTB:
    {
        res = cast_int(g->totalbytes & 1023);
        break;
    }
    case LUA_GCISRUNNING:
    {
        res = (g->GCthreshold != SIZE_MAX);
        break;
    }
    case LUA_GCSTEP:
    {
        size_t prevthreshold = g->GCthreshold;
        size_t amount = (cast_to(size_t, data) << 10);

        // temporarily adjust the threshold so that we can perform GC work
        if (amount <= g->totalbytes)
            g->GCthreshold = g->totalbytes - amount;
        else
            g->GCthreshold = 0;

        bool waspaused = g->gcstate == GCSpause;

        // track how much work the loop will actually perform
        size_t actualwork = 0;

        while (g->GCthreshold <= g->totalbytes)
        {
            luaC_step(L, false);

            actualwork += g->gcstepsize;

            if (g->gcstate == GCSpause)
            {            /* end of cycle? */
                res = 1; /* signal it */
                break;
            }
        }

        // if cycle hasn't finished, advance threshold forward for the amount of extra work performed
        if (g->gcstate != GCSpause)
        {
            // if a new cycle was triggered by explicit step, we ignore old threshold as that shows an incorrect 'credit' of GC work
            if (waspaused)
                g->GCthreshold = g->totalbytes + actualwork;
            else
                g->GCthreshold = prevthreshold + actualwork;
        }
        break;
    }
    case LUA_GCSETGOAL:
    {
        res = g->gcgoal;
        g->gcgoal = data;
        break;
    }
    case LUA_GCSETSTEPMUL:
    {
        res = g->gcstepmul;
        g->gcstepmul = data;
        break;
    }
    case LUA_GCSETSTEPSIZE:
    {
        /* GC values are expressed in Kbytes: #bytes/2^10 */
        res = g->gcstepsize >> 10;
        g->gcstepsize = data << 10;
        break;
    }
    default:
        res = -1; /* invalid option */
    }
    return res;
}

/*
** miscellaneous functions
*/

l_noret lua_error(lua_State* L)
{
    api_checknelems(L, 1);

    luaD_throw(L, LUA_ERRRUN);
}

int lua_next(lua_State* L, int idx)
{
    luaC_checkthreadsleep(L);
    StkId t = index2addr(L, idx);
    api_check(L, ttistable(t));
    int more = luaH_next(L, hvalue(t), L->top - 1);
    if (more)
    {
        api_incr_top(L);
    }
    else             /* no more elements */
        L->top -= 1; /* remove key */
    return more;
}

void lua_concat(lua_State* L, int n)
{
    api_checknelems(L, n);
    if (n >= 2)
    {
        luaC_checkGC(L);
        luaC_checkthreadsleep(L);
        luaV_concat(L, n, cast_int(L->top - L->base) - 1);
        L->top -= (n - 1);
    }
    else if (n == 0)
    { /* push empty string */
        luaC_checkthreadsleep(L);
        setsvalue2s(L, L->top, luaS_newlstr(L, "", 0));
        api_incr_top(L);
    }
    /* else n == 1; nothing to do */
    return;
}

void* lua_newuserdatatagged(lua_State* L, size_t sz, int tag)
{
    api_check(L, unsigned(tag) < LUA_UTAG_LIMIT);
    luaC_checkGC(L);
    luaC_checkthreadsleep(L);
    Udata* u = luaU_newudata(L, sz, tag);
    setuvalue(L, L->top, u);
    api_incr_top(L);
    return u->data;
}

void* lua_newuserdatadtor(lua_State* L, size_t sz, void (*dtor)(void*))
{
    luaC_checkGC(L);
    luaC_checkthreadsleep(L);
    Udata* u = luaU_newudata(L, sz + sizeof(dtor), UTAG_IDTOR);
    memcpy(&u->data + sz, &dtor, sizeof(dtor));
    setuvalue(L, L->top, u);
    api_incr_top(L);
    return u->data;
}

static const char* aux_upvalue(StkId fi, int n, TValue** val)
{
    Closure* f;
    if (!ttisfunction(fi))
        return NULL;
    f = clvalue(fi);
    if (f->isC)
    {
        if (!(1 <= n && n <= f->nupvalues))
            return NULL;
        *val = &f->c.upvals[n - 1];
        return "";
    }
    else
    {
        Proto* p = f->l.p;
        if (!(1 <= n && n <= p->sizeupvalues))
            return NULL;
        TValue* r = &f->l.uprefs[n - 1];
        *val = ttisupval(r) ? upvalue(r)->v : r;
        return getstr(p->upvalues[n - 1]);
    }
}

const char* lua_getupvalue(lua_State* L, int funcindex, int n)
{
    luaC_checkthreadsleep(L);
    TValue* val;
    const char* name = aux_upvalue(index2addr(L, funcindex), n, &val);
    if (name)
    {
        setobj2s(L, L->top, val);
        api_incr_top(L);
    }
    return name;
}

const char* lua_setupvalue(lua_State* L, int funcindex, int n)
{
    const char* name;
    TValue* val;
    StkId fi;
    fi = index2addr(L, funcindex);
    api_checknelems(L, 1);
    name = aux_upvalue(fi, n, &val);
    if (name)
    {
        L->top--;
        setobj(L, val, L->top);
        luaC_barrier(L, clvalue(fi), L->top);
        luaC_upvalbarrier(L, NULL, val);
    }
    return name;
}

uintptr_t lua_encodepointer(lua_State* L, uintptr_t p)
{
    global_State* g = L->global;
    return uintptr_t((g->ptrenckey[0] * p + g->ptrenckey[2]) ^ (g->ptrenckey[1] * p + g->ptrenckey[3]));
}

int lua_ref(lua_State* L, int idx)
{
    api_check(L, idx != LUA_REGISTRYINDEX); /* idx is a stack index for value */
    int ref = LUA_REFNIL;
    global_State* g = L->global;
    StkId p = index2addr(L, idx);
    if (!ttisnil(p))
    {
        Table* reg = hvalue(registry(L));

        if (g->registryfree != 0)
        { /* reuse existing slot */
            ref = g->registryfree;
        }
        else
        { /* no free elements */
            ref = luaH_getn(reg);
            ref++; /* create new reference */
        }

        TValue* slot = luaH_setnum(L, reg, ref);
        if (g->registryfree != 0)
            g->registryfree = int(nvalue(slot));
        setobj2t(L, slot, p);
        luaC_barriert(L, reg, p);
    }
    return ref;
}

void lua_unref(lua_State* L, int ref)
{
    if (ref <= LUA_REFNIL)
        return;

    global_State* g = L->global;
    Table* reg = hvalue(registry(L));
    TValue* slot = luaH_setnum(L, reg, ref);
    setnvalue(slot, g->registryfree); /* NB: no barrier needed because value isn't collectable */
    g->registryfree = ref;
    return;
}

void lua_setuserdatadtor(lua_State* L, int tag, void (*dtor)(void*))
{
    api_check(L, unsigned(tag) < LUA_UTAG_LIMIT);
    L->global->udatagc[tag] = dtor;
}

lua_Callbacks* lua_callbacks(lua_State* L)
{
    return &L->global->cb;
}