-
Notifications
You must be signed in to change notification settings - Fork 65
Expand file tree
/
Copy pathlib.zig
More file actions
5434 lines (4909 loc) · 207 KB
/
lib.zig
File metadata and controls
5434 lines (4909 loc) · 207 KB
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
//! Similar to the Lua C API documentation, each function has an indicator to describe how interacts with the stack and which errors it may return.
//!
//! Instead of using the form `[-o, +p, x]`, Zlua uses the words **Pops**, **Pushes**, and **Errors** for clarity.
//!
//! * **Pops**: how many elements the function pops from the stack.
//! * **Pushes**: how many elements the function pushes onto the stack.
//! (Any function always pushes its results after popping its arguments.)
//! * A field in the form `x|y` means the function can push (or pop) x or y elements, depending on the situation
//! * an interrogation mark `?` means that we cannot know how many elements the function pops/pushes by looking only at its arguments (For instance, they may depend on what is in the stack.)
//! * **Errors**: tells whether the function may raise errors:
//! * `-` means the function never raises any error
//! * `m` means the function may raise only out-of-memory errors
//! * `v` means the function may raise the errors explained in the text
//! * `e` means the function can run arbitrary Lua code, either directly or through metamethods, and therefore may raise any errors.
const std = @import("std");
pub const def = @import("define.zig");
pub const define = def.define;
const c = @import("c");
const config = @import("config");
/// Lua language version targeted
pub const lang = config.lang;
/// The length of Luau vector values, either 3 or 4.
pub const luau_vector_size = if (config.luau_use_4_vector) 4 else 3;
/// This function is defined in luau.cpp and must be called to define the assertion printer
extern "c" fn zig_registerAssertionHandler() void;
/// This function is defined in luau.cpp and ensures Zig uses the correct free when compiling luau code
extern "c" fn zig_luau_free(ptr: *anyopaque) void;
const Allocator = std.mem.Allocator;
// Types
//
// Lua constants and types are declared below in alphabetical order
// For constants that have a logical grouping (like Operators), Zig enums are used for type safety
const ArithOperator52 = enum(u4) {
add = c.LUA_OPADD,
sub = c.LUA_OPSUB,
mul = c.LUA_OPMUL,
div = c.LUA_OPDIV,
mod = c.LUA_OPMOD,
pow = c.LUA_OPPOW,
negate = c.LUA_OPUNM,
};
const ArithOperator53 = enum(u4) {
add = c.LUA_OPADD,
sub = c.LUA_OPSUB,
mul = c.LUA_OPMUL,
div = c.LUA_OPDIV,
int_div = c.LUA_OPIDIV,
mod = c.LUA_OPMOD,
pow = c.LUA_OPPOW,
negate = c.LUA_OPUNM,
bnot = c.LUA_OPBNOT,
band = c.LUA_OPBAND,
bor = c.LUA_OPBOR,
bxor = c.LUA_OPBXOR,
shl = c.LUA_OPSHL,
shr = c.LUA_OPSHR,
};
/// Operations supported by `Lua.arith()`
pub const ArithOperator = switch (lang) {
.lua53, .lua54 => ArithOperator53,
else => ArithOperator52,
};
/// Type for C functions
/// See https://www.lua.org/manual/5.4/manual.html#lua_CFunction for the protocol
pub const CFn = *const fn (state: ?*LuaState) callconv(.c) c_int;
/// Operations supported by `Lua.compare()`
pub const CompareOperator = enum(u2) {
eq = c.LUA_OPEQ,
lt = c.LUA_OPLT,
le = c.LUA_OPLE,
};
/// Type for C userdata destructors
pub const CUserdataDtorFn = *const fn (userdata: *anyopaque) callconv(.c) void;
/// Type for C interrupt callback
pub const CInterruptCallbackFn = *const fn (state: ?*LuaState, gc: c_int) callconv(.c) void;
/// Type for C useratom callback
pub const CUserAtomCallbackFn = *const fn (str: [*c]const u8, len: usize) callconv(.c) i16;
/// The internal Lua debug structure
const Debug = c.lua_Debug;
pub const DebugInfo51 = struct {
source: [:0]const u8 = undefined,
src_len: usize = 0,
short_src: [c.LUA_IDSIZE:0]u8 = undefined,
name: ?[:0]const u8 = undefined,
name_what: NameType = undefined,
what: FnType = undefined,
current_line: ?i32 = null,
first_line_defined: ?i32 = null,
last_line_defined: ?i32 = null,
is_vararg: bool = false,
private: c_int = undefined,
pub const NameType = enum { global, local, method, field, upvalue, other };
pub const FnType = enum { lua, c, main };
pub const Options = packed struct {
@">": bool = false,
f: bool = false,
l: bool = false,
n: bool = false,
S: bool = false,
u: bool = false,
L: bool = false,
fn toString(options: Options) [10:0]u8 {
var str = [_:0]u8{0} ** 10;
var index: u8 = 0;
inline for (std.meta.fields(Options)) |field| {
if (@field(options, field.name)) {
str[index] = field.name[0];
index += 1;
}
}
while (index < str.len) : (index += 1) str[index] = 0;
return str;
}
};
};
const DebugInfo52 = struct {
source: [:0]const u8 = undefined,
src_len: usize = 0,
short_src: [c.LUA_IDSIZE:0]u8 = undefined,
name: ?[:0]const u8 = undefined,
name_what: NameType = undefined,
what: FnType = undefined,
current_line: ?i32 = null,
first_line_defined: ?i32 = null,
last_line_defined: ?i32 = null,
num_upvalues: u8 = 0,
num_params: u8 = 0,
is_vararg: bool = false,
is_tail_call: bool = false,
private: *anyopaque = undefined,
pub const NameType = enum { global, local, method, field, upvalue, other };
pub const FnType = enum { lua, c, main };
pub const Options = packed struct {
@">": bool = false,
f: bool = false,
l: bool = false,
n: bool = false,
S: bool = false,
t: bool = false,
u: bool = false,
L: bool = false,
fn toString(options: Options) [10:0]u8 {
var str = [_:0]u8{0} ** 10;
var index: u8 = 0;
inline for (std.meta.fields(Options)) |field| {
if (@field(options, field.name)) {
str[index] = field.name[0];
index += 1;
}
}
while (index < str.len) : (index += 1) str[index] = 0;
return str;
}
};
};
/// The Lua debug interface structure
const DebugInfo54 = struct {
source: [:0]const u8 = undefined,
src_len: usize = 0,
short_src: [c.LUA_IDSIZE:0]u8 = undefined,
name: ?[:0]const u8 = undefined,
name_what: NameType = undefined,
what: FnType = undefined,
current_line: ?i32 = null,
first_line_defined: ?i32 = null,
last_line_defined: ?i32 = null,
num_upvalues: u8 = 0,
num_params: u8 = 0,
is_vararg: bool = false,
is_tail_call: bool = false,
first_transfer: u16 = 0,
num_transfer: u16 = 0,
private: *anyopaque = undefined,
pub const NameType = enum { global, local, method, field, upvalue, other };
pub const FnType = enum { lua, c, main };
pub const Options = packed struct {
@">": bool = false,
f: bool = false,
l: bool = false,
n: bool = false,
r: bool = false,
S: bool = false,
t: bool = false,
u: bool = false,
L: bool = false,
fn toString(options: Options) [10:0]u8 {
var str = [_:0]u8{0} ** 10;
var index: u8 = 0;
inline for (std.meta.fields(Options)) |field| {
if (@field(options, field.name)) {
str[index] = field.name[0];
index += 1;
}
}
while (index < str.len) : (index += 1) str[index] = 0;
return str;
}
};
};
pub const DebugInfoLuau = struct {
source: [:0]const u8 = undefined,
src_len: usize = 0,
short_src: [c.LUA_IDSIZE:0]u8 = undefined,
name: ?[:0]const u8 = undefined,
what: FnType = undefined,
current_line: ?i32 = null,
first_line_defined: ?i32 = null,
is_vararg: bool = false,
pub const NameType = enum { global, local, method, field, upvalue, other };
pub const FnType = enum { lua, c, main, tail };
pub const Options = packed struct {
f: bool = false,
l: bool = false,
n: bool = false,
s: bool = false,
u: bool = false,
L: bool = false,
fn toString(options: Options) [10:0]u8 {
var str = [_:0]u8{0} ** 10;
var index: u8 = 0;
inline for (std.meta.fields(Options)) |field| {
if (@field(options, field.name)) {
str[index] = field.name[0];
index += 1;
}
}
while (index < str.len) : (index += 1) str[index] = 0;
return str;
}
};
};
pub const DebugInfo = switch (lang) {
.lua51, .luajit => DebugInfo51,
.lua52, .lua53 => DebugInfo52,
.lua54 => DebugInfo54,
.luau => DebugInfoLuau,
};
/// The superset of all errors returned from zlua
pub const Error = error{
/// A generic failure (used when a function can only fail in one way)
LuaError,
/// A runtime error
LuaRuntime,
/// A syntax error during precompilation
LuaSyntax,
/// A memory allocation error
OutOfMemory,
/// An error while running the message handler
LuaMsgHandler,
/// A file-releated error
LuaFile,
} || switch (lang) {
.lua52, .lua53 => error{
/// A memory error in a __gc metamethod
LuaGCMetaMethod,
},
else => error{},
};
const Event51 = enum(u3) {
call = c.LUA_HOOKCALL,
ret = c.LUA_HOOKRET,
line = c.LUA_HOOKLINE,
count = c.LUA_HOOKCOUNT,
};
/// The type of event that triggers a hook
const Event52 = enum(u3) {
call = c.LUA_HOOKCALL,
ret = c.LUA_HOOKRET,
line = c.LUA_HOOKLINE,
count = c.LUA_HOOKCOUNT,
tail_call = c.LUA_HOOKTAILCALL,
};
pub const Event = switch (lang) {
.lua51, .luajit => Event51,
.lua52, .lua53, .lua54 => Event52,
// TODO: probably something better than void here
.luau => void,
};
/// Type for arrays of functions to be registered
pub const FnReg = struct {
name: [:0]const u8,
func: ?CFn,
};
/// The index of the global environment table
pub const globals_index = c.LUA_GLOBALSINDEX;
/// Type for debugging hook functions
pub const CHookFn = *const fn (state: ?*LuaState, ar: ?*Debug) callconv(.c) void;
/// Specifies on which events the hook will be called
pub const HookMask = packed struct {
call: bool = false,
ret: bool = false,
line: bool = false,
count: bool = false,
/// Converts a HookMask to an integer bitmask
pub fn toInt(mask: HookMask) i32 {
var bitmask: i32 = 0;
if (mask.call) bitmask |= mask_call;
if (mask.ret) bitmask |= mask_ret;
if (mask.line) bitmask |= mask_line;
if (mask.count) bitmask |= mask_count;
return bitmask;
}
/// Converts an integer bitmask into a HookMask
pub fn fromInt(mask: i32) HookMask {
return .{
.call = (mask & mask_call) != 0,
.ret = (mask & mask_ret) != 0,
.line = (mask & mask_line) != 0,
.count = (mask & mask_count) != 0,
};
}
};
/// Hook event codes
pub const hook_call = c.LUA_HOOKCALL;
pub const hook_count = c.LUA_HOOKCOUNT;
pub const hook_line = c.LUA_HOOKLINE;
pub const hook_ret = c.LUA_HOOKRET;
pub const hook_tail_call = c.LUA_HOOKTAILCALL;
/// Type of integers in Lua (typically an i64)
pub const Integer = c.lua_Integer;
/// Type for continuation-function contexts (usually isize)
pub const Context = isize;
/// Type for continuation functions
pub const CContFn = *const fn (state: ?*LuaState, status: c_int, ctx: Context) callconv(.c) c_int;
pub const Libs51 = packed struct {
base: bool = false,
package: bool = false,
string: bool = false,
utf8: bool = false,
table: bool = false,
math: bool = false,
io: bool = false,
os: bool = false,
debug: bool = false,
};
pub const Libs52 = packed struct {
base: bool = false,
coroutine: bool = false,
package: bool = false,
string: bool = false,
table: bool = false,
math: bool = false,
io: bool = false,
os: bool = false,
debug: bool = false,
bit: bool = false,
};
pub const Libs53 = packed struct {
base: bool = false,
coroutine: bool = false,
package: bool = false,
string: bool = false,
utf8: bool = false,
table: bool = false,
math: bool = false,
io: bool = false,
os: bool = false,
debug: bool = false,
};
/// The type of the opaque structure that points to a thread and the state of a Lua interpreter
pub const LuaState = c.lua_State;
/// Lua types
/// Must be a signed integer because LuaType.none is -1
pub const LuaType = switch (lang) {
.luau => enum(i5) {
none = c.LUA_TNONE,
nil = c.LUA_TNIL,
boolean = c.LUA_TBOOLEAN,
light_userdata = c.LUA_TLIGHTUSERDATA,
number = c.LUA_TNUMBER,
vector = c.LUA_TVECTOR,
string = c.LUA_TSTRING,
table = c.LUA_TTABLE,
function = c.LUA_TFUNCTION,
userdata = c.LUA_TUSERDATA,
thread = c.LUA_TTHREAD,
},
else => enum(i5) {
none = c.LUA_TNONE,
nil = c.LUA_TNIL,
boolean = c.LUA_TBOOLEAN,
light_userdata = c.LUA_TLIGHTUSERDATA,
number = c.LUA_TNUMBER,
string = c.LUA_TSTRING,
table = c.LUA_TTABLE,
function = c.LUA_TFUNCTION,
userdata = c.LUA_TUSERDATA,
thread = c.LUA_TTHREAD,
},
};
/// Modes used for `Lua.load()`
pub const Mode = enum(u2) { binary, text, binary_text };
/// Event masks
pub const mask_call = c.LUA_MASKCALL;
pub const mask_count = c.LUA_MASKCOUNT;
pub const mask_line = c.LUA_MASKLINE;
pub const mask_ret = c.LUA_MASKRET;
/// The maximum integer value that `Integer` can store
pub const max_integer = c.LUA_MAXINTEGER;
/// The minimum integer value that `Integer` can store
pub const min_integer = c.LUA_MININTEGER;
/// The minimum Lua stack available to a function
pub const min_stack = c.LUA_MINSTACK;
/// Option for multiple returns in `Lua.protectedCall()` and `Lua.call()`
pub const mult_return = c.LUA_MULTRET;
/// Type of floats in Lua (typically an f64)
pub const Number = c.lua_Number;
/// The type of the reader function used by `Lua.load()`
pub const CReaderFn = *const fn (state: ?*LuaState, data: ?*anyopaque, size: [*c]usize) callconv(.c) [*c]const u8;
/// The possible status of a call to `Lua.resumeThread`
pub const ResumeStatus = enum(u1) {
ok = StatusCode.ok,
yield = StatusCode.yield,
};
/// Reference constants
pub const ref_nil = c.LUA_REFNIL;
pub const ref_no = c.LUA_NOREF;
/// Index of the regsitry in the stack (pseudo-index)
pub const registry_index = c.LUA_REGISTRYINDEX;
/// Index of globals in the registry
pub const ridx_globals = c.LUA_RIDX_GLOBALS;
/// Index of the main thread in the registry
pub const ridx_mainthread = c.LUA_RIDX_MAINTHREAD;
/// Status that a thread can be in
/// Usually errors are reported by a Zig error rather than a status enum value
pub const Status = enum(u3) {
ok = StatusCode.ok,
yield = StatusCode.yield,
err_runtime = StatusCode.err_runtime,
err_syntax = StatusCode.err_syntax,
err_memory = StatusCode.err_memory,
err_error = StatusCode.err_error,
};
/// Status codes
/// Not public, because typically Status.ok is returned from a function implicitly;
/// Any function that returns an error usually returns a Zig error, and a void return
/// is an implicit Status.ok.
/// In the rare case that the status code is required from a function, an enum is
/// used for that specific function's return type
/// TODO: see where this is used and check if a null can be used instead
const StatusCode = struct {
pub const ok = if (@hasDecl(c, "LUA_OK")) c.LUA_OK else 0;
pub const yield = c.LUA_YIELD;
pub const err_runtime = c.LUA_ERRRUN;
pub const err_syntax = c.LUA_ERRSYNTAX;
pub const err_memory = c.LUA_ERRMEM;
pub const err_error = c.LUA_ERRERR;
pub const err_gcmm = switch (lang) {
.lua52, .lua53 => c.LUA_ERRGCMM,
else => unreachable,
};
};
// Only used in loadFileX, so no need to group with Status
pub const err_file = c.LUA_ERRFILE;
/// The standard representation for file handles used by the standard IO library
pub const Stream = c.luaL_Stream;
/// The unsigned version of Integer
pub const Unsigned = c.lua_Unsigned;
/// The type of warning functions used by Lua to emit warnings
pub const CWarnFn = switch (lang) {
.lua54 => *const fn (data: ?*anyopaque, msg: [*c]const u8, to_cont: c_int) callconv(.c) void,
else => @compileError("CWarnFn not defined"),
};
/// The type of the writer function used by `Lua.dump()`
pub const CWriterFn = *const fn (state: ?*LuaState, buf: ?*const anyopaque, size: usize, data: ?*anyopaque) callconv(.c) c_int;
/// For bundling a parsed value with an arena allocator
/// Copied from std.json.Parsed
pub fn Parsed(comptime T: type) type {
return struct {
arena: *std.heap.ArenaAllocator,
value: T,
pub fn deinit(self: @This()) void {
const allocator = self.arena.child_allocator;
self.arena.deinit();
allocator.destroy(self.arena);
}
};
}
/// A Zig wrapper around the Lua C API
/// Represents a Lua state or thread and contains the entire state of the Lua interpreter
pub const Lua = opaque {
const alignment = @alignOf(std.c.max_align_t);
/// Allows Lua to allocate memory using a Zig allocator passed in via data.
/// See https://www.lua.org/manual/5.4/manual.html#lua_Alloc for more details
fn alloc(data: ?*anyopaque, ptr: ?*anyopaque, osize: usize, nsize: usize) callconv(.c) ?*align(alignment) anyopaque {
// just like malloc() returns a pointer "which is suitably aligned for any built-in type",
// the memory allocated by this function should also be aligned for any type that Lua may
// desire to allocate. use the largest alignment for the target
const allocator_ptr: *Allocator = @ptrCast(@alignCast(data.?));
if (@as(?[*]align(alignment) u8, @ptrCast(@alignCast(ptr)))) |prev_ptr| {
const prev_slice = prev_ptr[0..osize];
// when nsize is zero the allocator must behave like free and return null
if (nsize == 0) {
allocator_ptr.free(prev_slice);
return null;
}
// when nsize is not zero the allocator must behave like realloc
const new_ptr = allocator_ptr.realloc(prev_slice, nsize) catch return null;
return new_ptr.ptr;
} else if (nsize == 0) {
return null;
} else {
const builtin = @import("builtin"); // FIXME: remove when zig-0.15 is released and 0.14 can be dropped
// ptr is null, allocate a new block of memory
const new_ptr = (if (builtin.zig_version.major == 0 and builtin.zig_version.minor < 15)
allocator_ptr.alignedAlloc(u8, alignment, nsize)
else
allocator_ptr.alignedAlloc(u8, .fromByteUnits(alignment), nsize)) catch return null;
return new_ptr.ptr;
}
}
/// Initialize a Lua state with the given allocator. Use `Lua.deinit()` to close the state and free memory.
///
/// Creates a new independent state and returns its main thread.
/// Returns an error if it cannot create the state (due to lack of memory).
/// Lua will do all memory allocation for this state through the passed Allocator (see lua_Alloc).
///
/// * Pops: `0`
/// * Pushes: `0`
/// * Errors: `never`
///
/// See https://www.lua.org/manual/5.4/manual.html#lua_newstate
pub fn init(a: Allocator) !*Lua {
if (lang == .luau) zig_registerAssertionHandler();
// the userdata passed to alloc needs to be a pointer with a consistent address
// so we allocate an Allocator struct to hold a copy of the allocator's data
const allocator_ptr = try a.create(Allocator);
allocator_ptr.* = a;
if (c.lua_newstate(alloc, allocator_ptr)) |state| {
return @ptrCast(state);
} else return error.OutOfMemory;
}
/// Deinitialize a Lua state and free all memory
///
/// See https://www.lua.org/manual/5.4/manual.html#lua_close
pub fn deinit(lua: *Lua) void {
// First get a reference to the allocator
var data: ?*Allocator = undefined;
_ = c.lua_getallocf(@ptrCast(lua), @ptrCast(&data)).?;
c.lua_close(@ptrCast(lua));
if (data) |a| {
const alloc_ = a;
alloc_.destroy(a);
}
}
/// Returns the `std.mem.Allocator` used to initialize this Lua state
pub fn allocator(lua: *Lua) Allocator {
var data: ?*Allocator = undefined;
_ = c.lua_getallocf(@ptrCast(lua), @ptrCast(&data)).?;
// The pointer should never be null because the only way to create a Lua state requires
// passing a Zig allocator.
// Although the Allocator is passed to Lua as a pointer, return a copy to make use more convenient.
return data.?.*;
}
// Library functions
//
// Library functions are included in alphabetical order.
// Each is kept similar to the original C API function while also making it easy to use from Zig
/// Converts the acceptable index idx into an equivalent absolute index (that is, one that does not depend on the stack size)
///
/// * Pops: `0`
/// * Pushes: `0`
/// * Errors: `never`
///
/// See https://www.lua.org/manual/5.4/manual.html#lua_absindex
pub fn absIndex(lua: *Lua, index: i32) i32 {
switch (lang) {
.lua51, .luajit => {
if (index > 0 or index <= registry_index) {
return index;
} else {
const result = lua.getTop() + 1 + index;
return @intCast(result);
}
},
else => {
return c.lua_absindex(@ptrCast(lua), index);
},
}
}
/// Arithmetic functions for values on the stack
///
/// Performs an arithmetic or bitwise operation over the two values (or one, in the
/// case of negations) at the top of the stack, with the value on the top being the
/// second operand, pops these values, and pushes the result of the operation. The
/// function follows the semantics of the corresponding Lua operator (that is, it
/// may call metamethods).
///
/// Not implemented in Lua 5.1, LuaJIT, or Luau
///
/// * Pops: `(2|1)`
/// * Pushes: `1`
/// * Errors: `other`
///
/// See https://www.lua.org/manual/5.4/manual.html#lua_arith
pub fn arith(lua: *Lua, op: ArithOperator) void {
c.lua_arith(@ptrCast(lua), @intFromEnum(op));
}
/// Sets a new panic function and returns the old one
///
/// Not implemented in Luau
///
/// * Pops: `0`
/// * Pushes: `0`
/// * Errors: `never`
///
/// See https://www.lua.org/manual/5.4/manual.html#lua_atpanic
pub fn atPanic(lua: *Lua, panic_fn: CFn) ?CFn {
if (lang == .luau) @compileError(@src().fn_name ++ " is not implemented in Luau.");
return c.lua_atpanic(@ptrCast(lua), panic_fn);
}
pub const CallArgs = struct {
/// The number of args passed to the function from the stack
args: i32 = 0,
/// The number of results the function pushes to the stack upon returning
results: i32 = 0,
};
/// Calls a function
///
/// Like regular Lua calls, `Lua.call()` respects the `__call` metamethod. So, here the word "function" means any callable value.
///
/// To do a call you must use the following protocol:
/// * First, the function to be called is pushed onto the stack
/// * Then, the arguments to the call are pushed in direct order that is, the first argument is pushed first.
/// * Finally you call `Lua.call()`
/// * `args.args` is the number of arguments that you pushed onto the stack. When the function returns, all arguments and
/// the function value are popped and the call results are pushed onto the stack.
/// * The number of results is adjusted to `args.results`, unless `args.results` is `zlua.mult_return`. In this case, all results from the function are pushed
/// * Lua takes care that the returned values fit into the stack space, but it does not ensure any extra space in the stack. The function results
/// are pushed onto the stack in direct order (the first result is pushed first), so that after the call the last result is
/// on the top of the stack.
///
/// Any error while calling and running the function is propagated upwards (with a longjmp).
///
/// * Pops: `(args.args+1)`
/// * Pushes: `args.results`
/// * Errors: `other`
///
/// See https://www.lua.org/manual/5.4/manual.html#lua_call
pub fn call(lua: *Lua, args: CallArgs) void {
switch (lang) {
.lua51, .luajit, .luau => c.lua_call(@ptrCast(lua), args.args, args.results),
else => c.lua_callk(@ptrCast(lua), args.args, args.results, 0, null),
}
}
/// Continuations are supported in Lua 5.2, 5.3, and 5.4
/// See https://www.lua.org/manual/5.4/manual.html#4.5
pub const CallContArgs = struct {
/// The number of args passed to the function from the stack
args: i32 = 0,
/// The number of results the function pushes to the stack upon returning
results: i32 = 0,
/// Context value passed to the continuation function
ctx: switch (lang) {
.lua52 => i32,
.lua53, .lua54 => Context,
else => void,
},
/// The continuation function
k: switch (lang) {
.lua52 => CFn,
.lua53, .lua54 => CContFn,
else => void,
},
};
/// This function behaves exactly like `Lua.call()`, but allows the called function to yield
///
/// Not implemented in Lua 5.1, LuaJIT, or Luau
///
/// * Pops: `(args.args + 1)`
/// * Pushes: `args.results`
/// * Errors: `other`
///
/// See https://www.lua.org/manual/5.4/manual.html#lua_callk
pub fn callCont(lua: *Lua, args: CallContArgs) void {
c.lua_callk(@ptrCast(lua), args.args, args.results, args.ctx, args.k);
}
/// Ensures that the stack has space for at least `n` extra elements, that is, that you can safely push up to `n` values into
/// it. It returns an error if it cannot fulfill the request, either because it would cause the stack to be greater than a
/// fixed maximum size (typically at least several thousand elements) or because it cannot allocate memory for the extra
/// space. This function never shrinks the stack; if the stack already has space for the extra elements, it is left
/// unchanged.
///
/// * Pops: `0`
/// * Pushes: `0`
/// * Errors: `memory` (Lua 5.1, LuaJIT, Luau)
/// * Errors: `never` (Lua 5.2, 5.3, 5.4)
///
/// See https://www.lua.org/manual/5.4/manual.html#lua_checkstack
pub fn checkStack(lua: *Lua, n: i32) !void {
if (c.lua_checkstack(@ptrCast(lua), n) == 0) return error.LuaError;
}
/// Close the to-be-closed slot at the given index and set its value to nil. The index must be the last index previously
/// marked to be closed (see `Lua.toClose()`) that is still active (that is, not closed yet).
/// A `__close` metamethod cannot yield when called through this function.
///
/// Only implemented in Lua 5.4
///
/// * Pops: `0`
/// * Pushes: `0`
/// * Errors: `other`
///
/// See https://www.lua.org/manual/5.4/manual.html#lua_closeslot
pub fn closeSlot(lua: *Lua, index: i32) void {
c.lua_closeslot(@ptrCast(lua), index);
}
/// Resets a thread, cleaning its call stack and closing all pending to-be-closed variables. Returns an
/// error status if an error occurs and leaves the error object on the top of the stack.
///
/// The parameter `from` represents the coroutine that is resetting `lua`. If there is no such coroutine, this parameter can be
/// `null`.
///
/// Only implemented in Lua 5.4
///
/// * Pops: `0`
/// * Pushes: `?`
/// * Errors: `never`
///
/// See https://www.lua.org/manual/5.4/manual.html#lua_closethread
pub fn closeThread(lua: *Lua, from: ?*Lua) !void {
if (c.lua_closethread(@ptrCast(lua), if (from) |f| @ptrCast(f) else null) != StatusCode.ok) return error.LuaError;
}
/// Compares two Lua values.
///
/// Returns `true` if the value at index `index1` satisfies `op` when compared with the value at index
/// `index2`, following the semantics of the corresponding Lua operator (that is, it may call metamethods). Otherwise returns
/// `false`. Also returns `false` if any of the indices is not valid.
///
/// Not implemented in Lua 5.1, LuaJIT, or Luau
///
/// * Pops: `0`
/// * Pushes: `0`
/// * Errors: `other`
///
/// See https://www.lua.org/manual/5.4/manual.html#lua_compare
pub fn compare(lua: *Lua, index1: i32, index2: i32, op: CompareOperator) bool {
return c.lua_compare(@ptrCast(lua), index1, index2, @intFromEnum(op)) != 0;
}
/// Concatenates the `n` values at the top of the stack, pops them, and leaves the result at the top
/// If the number of values is 1, the result is a single value on the stack (nothing changes)
/// If the number of values is 0, the result is the empty string
///
/// * Pops: `n`
/// * Pushes: `1`
/// * Errors: `other`
///
/// See https://www.lua.org/manual/5.4/manual.html#lua_concat
pub fn concat(lua: *Lua, n: i32) void {
c.lua_concat(@ptrCast(lua), n);
}
/// Calls the C function `c_fn` in protected mode. `c_fn` starts with only one element in its stack, a light userdata
/// containing `userdata`. In case of errors, `Lua.cProtectedCall()` returns the same error codes as `Lua.protectedCall()`, plus the error object on the
/// top of the stack; otherwise, it returns zero, and does not change the stack. All values returned by `c_fn` are discarded.
///
/// Only implemented in Lua 5.1
///
/// * Pops: `0`
/// * Pushes: `(0|1)`
/// * Errors: `never`
///
/// See https://www.lua.org/manual/5.1/manual.html#lua_cpcall
pub fn cProtectedCall(lua: *Lua, c_fn: CFn, userdata: *anyopaque) !void {
const ret = c.lua_cpcall(@ptrCast(lua), c_fn, userdata);
switch (ret) {
StatusCode.ok => return,
StatusCode.err_runtime => return error.LuaRuntime,
StatusCode.err_memory => return error.OutOfMemory,
StatusCode.err_error => return error.LuaMsgHandler,
else => unreachable,
}
}
/// Copies the element at index `from_index` into the valid index `to_index`, replacing the value at that position. Values at other
/// positions are not affected.
///
/// Not implemented in Lua 5.1, LuaJIT, or Luau
///
/// * Pops: `0`
/// * Pushes: `0`
/// * Errors: `never`
///
/// See https://www.lua.org/manual/5.4/manual.html#lua_copy
pub fn copy(lua: *Lua, from_index: i32, to_index: i32) void {
c.lua_copy(@ptrCast(lua), from_index, to_index);
}
/// Creates a new empty table and pushes it onto the stack.
///
/// Parameter `num_arr` is a hint for how many elements the table will
/// have as a sequence; parameter `num_rec` is a hint for how many other elements the table will have. Lua may use these hints
/// to preallocate memory for the new table. This preallocation may help performance when you know in advance how many
/// elements the table will have. Otherwise you can use the function `Lua.newTable()`.
///
/// * Pops: `0`
/// * Pushes: `1`
/// * Errors `other` (Lua 5.2)
/// * Errors: `memory` (other)
///
/// See https://www.lua.org/manual/5.4/manual.html#lua_createtable
pub fn createTable(lua: *Lua, num_arr: i32, num_rec: i32) void {
c.lua_createtable(@ptrCast(lua), num_arr, num_rec);
}
fn dump51(lua: *Lua, writer: CWriterFn, data: *anyopaque) !void {
if (c.lua_dump(@ptrCast(lua), writer, data) != 0) return error.LuaError;
}
fn dump53(lua: *Lua, writer: CWriterFn, data: *anyopaque, strip: bool) !void {
if (c.lua_dump(@ptrCast(lua), writer, data, @intFromBool(strip)) != 0) return error.LuaError;
}
/// Dumps a function as a binary chunk.
///
/// Receives a Lua function on the top of the stack and produces a binary chunk that,
/// if loaded again, results in a function equivalent to the one dumped. As it produces parts of the chunk, `Lua.dump()` calls
/// function `writer` (see `CWriterFn`) with the given data to write them.
///
/// For Lua 5.3 and 5.4:
/// If `strip` is true, the binary representation may not include all debug information about the function, to save space.
///
/// Returns an error code if the last call to the writer function fails
///
/// This function does not pop the Lua function from the stack.
///
/// Not implemented in Luau
///
/// * Pops: `0`
/// * Pushes: `0`
/// * Errors: `memory` (Lua 5.1, LuaJIT)
/// * Errors: `other` (Lua 5.2)
/// * Errors: `never` (Lua 5.3, 5.4)
///
/// See https://www.lua.org/manual/5.4/manual.html#lua_dump
pub const dump = switch (lang) {
.lua53, .lua54 => dump53,
else => dump51,
.luau => @compileError("Not implemented in Luau."),
};
/// Returns `true` if the two values in acceptable indices `index1` and `index2` are equal, following the semantics of the Lua `==`
/// operator (that is, may call metamethods). Otherwise returns `false`. Also returns `false` if any of the indices is non valid.
///
/// Not implemented in Lua 5.2, 5.3, or 5.4
///
/// * Pops: `0`
/// * Pushes: `0`
/// * Errors: `other`
///
/// See https://www.lua.org/manual/5.1/manual.html#lua_equal
pub fn equal(lua: *Lua, index1: i32, index2: i32) bool {
switch (lang) {
.lua52, .lua53, .lua54 => @compileError("lua_equal is deprecated, use Lua.compare with .eq instead"),
else => {},
}
return c.lua_equal(@ptrCast(lua), index1, index2) == 1;
}
/// Raises a Lua error, using the value on the top of the stack as the error object. This function does a long jump, and
/// therefore never returns (see `Lua.raiseErrorStr()`).
///
/// * Pops: `1`
/// * Pushes: `0`
/// * Errors: `explained in text / on purpose`
///