forked from natecraddock/ziglua
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathziglua.zig
More file actions
1956 lines (1654 loc) · 75 KB
/
Copy pathziglua.zig
File metadata and controls
1956 lines (1654 loc) · 75 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
//! ziglua.zig: complete bindings around the Lua C API version 5.4.4
//! exposes all Lua functionality, with additional Zig helper functions
const std = @import("std");
const c = @cImport({
@cInclude("lua.h");
@cInclude("lualib.h");
@cInclude("lauxlib.h");
});
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
/// The type of function that Lua uses for all internal allocations and frees
/// `data` is an opaque pointer to any data (the allocator), `ptr` is a pointer to the block being alloced/realloced/freed
/// `osize` is the original size or a code, and `nsize` is the new size
///
/// See https://www.lua.org/manual/5.4/manual.html#lua_Alloc for more details
pub const AllocFn = fn (data: ?*anyopaque, ptr: ?*anyopaque, osize: usize, nsize: usize) callconv(.C) ?*anyopaque;
/// Operations supported by `Lua.arith()`
/// TODO: use longer names
pub const ArithOperator = enum(u4) {
add = c.LUA_OPADD,
sub = c.LUA_OPSUB,
mul = c.LUA_OPMUL,
div = c.LUA_OPDIV,
idiv = c.LUA_OPIDIV,
mod = c.LUA_OPMOD,
pow = c.LUA_OPPOW,
unm = 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,
};
/// Type for C functions
/// See https://www.lua.org/manual/5.4/manual.html#lua_CFunction for the protocol
pub const CFn = 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,
};
/// The internal Lua debug structure
const Debug = c.lua_Debug;
/// The Lua debug interface structure
pub const DebugInfo = 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;
}
};
};
/// The superset of all errors returned from ziglua
pub const Error = error{
/// A generic failure (used when a function can only fail in one way)
Fail,
/// A runtime error
Runtime,
/// A syntax error during precompilation
Syntax,
/// A memory allocation error
Memory,
/// An error while running the message handler
MsgHandler,
/// A file-releated error
File,
};
/// The type of event that triggers a hook
pub const Event = enum(u3) {
call = c.LUA_HOOKCALL,
ret = c.LUA_HOOKRET,
line = c.LUA_HOOKLINE,
count = c.LUA_HOOKCOUNT,
tail_call = c.LUA_HOOKTAILCALL,
};
/// Type for arrays of functions to be registered
pub const FnReg = struct {
name: [:0]const u8,
func: ?CFn,
};
/// Type for debugging hook functions
pub const CHookFn = 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 = fn (state: ?*LuaState, status: c_int, ctx: Context) callconv(.C) c_int;
/// Bitflag for the Lua standard libraries
pub const Libs = 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 = 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 = 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
const StatusCode = struct {
pub const ok = c.LUA_OK;
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;
};
// 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 = fn (data: ?*anyopaque, msg: [*c]const u8, to_cont: c_int) callconv(.C) void;
/// The type of the writer function used by `Lua.dump()`
pub const CWriterFn = fn (state: ?*LuaState, buf: ?*const anyopaque, size: usize, data: ?*anyopaque) callconv(.C) c_int;
/// 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 = struct {
allocator: ?*Allocator = null,
state: *LuaState,
/// 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) ?*anyopaque {
_ = osize; // unused
// 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 alignment = @alignOf(std.c.max_align_t);
// the data pointer is an Allocator, so the @alignCast is safe
const allocator = opaqueCast(Allocator, data.?);
if (@ptrCast(?[*]align(alignment) u8, @alignCast(alignment, 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.free(prev_slice);
return null;
}
// when nsize is not zero the allocator must behave like realloc
const new_ptr = allocator.reallocAdvanced(prev_slice, alignment, nsize, .exact) catch return null;
return new_ptr.ptr;
} else {
// ptr is null, allocate a new block of memory
const new_ptr = allocator.alignedAlloc(u8, alignment, nsize) catch return null;
return new_ptr.ptr;
}
}
/// Initialize a Lua state with the given allocator
pub fn init(allocator: Allocator) !Lua {
// 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
var allocator_ptr = allocator.create(Allocator) catch return error.Memory;
allocator_ptr.* = allocator;
const state = c.lua_newstate(alloc, allocator_ptr) orelse return error.Memory;
return Lua{
.allocator = allocator_ptr,
.state = state,
};
}
/// Deinitialize a Lua state and free all memory
pub fn deinit(lua: *Lua) void {
lua.close();
if (lua.allocator) |a| {
const allocator = a;
allocator.destroy(a);
lua.allocator = null;
}
}
// 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 `index` into an equivalent absolute index
pub fn absIndex(lua: *Lua, index: i32) i32 {
return c.lua_absindex(lua.state, index);
}
/// Performs an arithmetic or bitwise operation over the value(s) at the top of the stack
/// This function follows the semantics of the corresponding Lua operator
pub fn arith(lua: *Lua, op: ArithOperator) void {
c.lua_arith(lua.state, @enumToInt(op));
}
/// Sets a new panic function and returns the old one
pub fn atPanic(lua: *Lua, panic_fn: CFn) ?CFn {
return c.lua_atpanic(lua.state, panic_fn);
}
/// Calls a function (or any callable value)
pub fn call(lua: *Lua, num_args: i32, num_results: i32) void {
lua.callCont(num_args, num_results, 0, null);
}
/// Like `call`, but allows the called function to yield
pub fn callCont(lua: *Lua, num_args: i32, num_results: i32, ctx: Context, k: ?CContFn) void {
c.lua_callk(lua.state, num_args, num_results, ctx, k);
}
/// Ensures that the stack has space for at least `n` extra arguments
/// Returns an error if it cannot fulfil the request
/// Never shrinks the stack
pub fn checkStack(lua: *Lua, n: i32) !void {
if (c.lua_checkstack(lua.state, n) == 0) return error.Fail;
}
/// Release all Lua objects in the state and free all dynamic memory
pub fn close(lua: *Lua) void {
c.lua_close(lua.state);
}
/// Close the to-be-closed slot at the given `index` and set the value to nil
pub fn closeSlot(lua: *Lua, index: i32) void {
c.lua_closeslot(lua.state, index);
}
/// Compares two Lua values
/// Returns true if the value at `index1` satisfies `op` when compared with the value at `index2`
/// Returns false otherwise, or if any index is not valid
pub fn compare(lua: *Lua, index1: i32, index2: i32, op: CompareOperator) bool {
// TODO: perhaps support gt/ge by swapping args...
return c.lua_compare(lua.state, index1, index2, @enumToInt(op)) != 0;
}
/// Concatenates the `n` values at the top of the stack, pops them, and leaves the result at the top
/// If `n` is 1, the result is a single value on the stack (nothing changes)
/// If `n` is 0, the result is the empty string
pub fn concat(lua: *Lua, n: i32) void {
c.lua_concat(lua.state, n);
}
/// Copies the element at `from_index` to the valid index `to_index`, replacing the value at that position
pub fn copy(lua: *Lua, from_index: i32, to_index: i32) void {
c.lua_copy(lua.state, from_index, to_index);
}
/// Creates a new empty table and pushes onto the stack
/// `num_arr` is a hint for how many elements the table will have as a sequence
/// `num_rec` is a hint for how many other elements the table will have
/// Lua may preallocate memory for the table based on the hints
pub fn createTable(lua: *Lua, num_arr: i32, num_rec: i32) void {
c.lua_createtable(lua.state, num_arr, num_rec);
}
/// Dumps a function as a binary chunk
/// Returns an error if writing was unsuccessful
pub fn dump(lua: *Lua, writer: CWriterFn, data: *anyopaque, strip: bool) !void {
if (c.lua_dump(lua.state, writer, data, @boolToInt(strip)) != 0) return error.Fail;
}
/// Raises a Lua error using the value at the top of the stack as the error object
/// Does a longjump and therefore never returns
pub fn raiseError(lua: *Lua) noreturn {
_ = c.lua_error(lua.state);
unreachable;
}
/// Perform a full garbage-collection cycle
pub fn gcCollect(lua: *Lua) void {
_ = c.lua_gc(lua.state, c.LUA_GCCOLLECT);
}
/// Stops the garbage collector
pub fn gcStop(lua: *Lua) void {
_ = c.lua_gc(lua.state, c.LUA_GCSTOP);
}
/// Restarts the garbage collector
pub fn gcRestart(lua: *Lua) void {
_ = c.lua_gc(lua.state, c.LUA_GCRESTART);
}
/// Performs an incremental step of garbage collection corresponding to the allocation of `step_size` Kbytes
pub fn gcStep(lua: *Lua, step_size: i32) void {
_ = c.lua_gc(lua.state, c.LUA_GCSTEP, step_size);
}
/// Returns the current amount of memory (in Kbytes) in use by Lua
pub fn gcCount(lua: *Lua) i32 {
return c.lua_gc(lua.state, c.LUA_GCCOUNT);
}
/// Returns the remainder of dividing the current amount of bytes of memory in use by Lua by 1024
pub fn gcCountB(lua: *Lua) i32 {
return c.lua_gc(lua.state, c.LUA_GCCOUNTB);
}
/// Returns a boolean that tells whether the garbage collector is running
pub fn gcIsRunning(lua: *Lua) bool {
return c.lua_gc(lua.state, c.LUA_GCISRUNNING) != 0;
}
/// Changes the collector to incremental mode
/// Returns true if the previous mode was generational
pub fn gcSetIncremental(lua: *Lua, pause: i32, step_mul: i32, step_size: i32) bool {
return c.lua_gc(lua.state, c.LUA_GCINC, pause, step_mul, step_size) == c.LUA_GCGEN;
}
/// Changes the collector to generational mode
/// Returns true if the previous mode was incremental
pub fn gcSetGenerational(lua: *Lua, minor_mul: i32, major_mul: i32) bool {
return c.lua_gc(lua.state, c.LUA_GCGEN, minor_mul, major_mul) == c.LUA_GCINC;
}
/// Returns the memory allocation function of a given state
/// If `data` is not null, it is set to the opaque pointer given when the allocator function was set
pub fn getAllocF(lua: *Lua, data: ?**anyopaque) AllocFn {
// Assert cannot be null because it is impossible (and not useful) to pass null
// to the functions that set the allocator (setallocf and newstate)
return c.lua_getallocf(lua.state, @ptrCast([*c]?*anyopaque, data)).?;
}
/// Returns a slice of a raw memory area associated with the given Lua state
/// The application may use this area for any purpose; Lua does not use it for anything
pub fn getExtraSpace(lua: *Lua) []u8 {
return @ptrCast([*]u8, c.lua_getextraspace(lua.state).?)[0..@sizeOf(isize)];
}
/// Pushes onto the stack the value t[key] where t is the value at the given `index`
pub fn getField(lua: *Lua, index: i32, key: [:0]const u8) LuaType {
return @intToEnum(LuaType, c.lua_getfield(lua.state, index, key));
}
/// Pushes onto the stack the value of the global `name`
/// Returns an error if the global does not exist (is nil)
pub fn getGlobal(lua: *Lua, name: [:0]const u8) !void {
_ = try lua.getGlobalEx(name);
}
/// Pushes onto the stack the value of the global `name`. Returns the type of that value
/// Returns an error if the global does not exist (is nil)
pub fn getGlobalEx(lua: *Lua, name: [:0]const u8) !LuaType {
const lua_type = @intToEnum(LuaType, c.lua_getglobal(lua.state, name));
if (lua_type == .nil) return error.Fail;
return lua_type;
}
/// Pushes onto the stack the value t[`i`] where t is the value at the given `index`
/// Returns the type of the pushed value
pub fn getIndex(lua: *Lua, index: i32, i: Integer) LuaType {
return @intToEnum(LuaType, c.lua_geti(lua.state, index, i));
}
/// Pushes onto the stack the `n`th user value associated with the full userdata at the given `index`
/// Returns the type of the pushed value
/// Returns an error if the userdata does not have that value
pub fn getIndexUserValue(lua: *Lua, index: i32, n: i32) !LuaType {
const val_type = @intToEnum(LuaType, c.lua_getiuservalue(lua.state, index, n));
if (val_type == .none) return error.Fail;
return val_type;
}
/// If the value at the given `index` has a metatable, the function pushes that metatable onto the stack
/// Otherwise an error is returned
pub fn getMetatable(lua: *Lua, index: i32) !void {
if (c.lua_getmetatable(lua.state, index) == 0) return error.Fail;
}
/// Pushes onto the stack the value t[k] where t is the value at the given `index` and k is the value on the top of the stack
/// Returns the type of the pushed value
pub fn getTable(lua: *Lua, index: i32) LuaType {
return @intToEnum(LuaType, c.lua_gettable(lua.state, index));
}
/// Returns the index of the top element in the stack
/// Because indices start at 1, the result is also equal to the number of elements in the stack
pub fn getTop(lua: *Lua) i32 {
return c.lua_gettop(lua.state);
}
/// Moves the top element into the given valid `index` shifting up any elements to make room
pub fn insert(lua: *Lua, index: i32) void {
// translate-c cannot translate this macro correctly
// c.lua_insert(lua.state, index);
lua.rotate(index, 1);
}
/// Returns true if the value at the given `index` is a boolean
pub fn isBoolean(lua: *Lua, index: i32) bool {
return c.lua_isboolean(lua.state, index);
}
/// Returns true if the value at the given `index` is a CFn
pub fn isCFunction(lua: *Lua, index: i32) bool {
return c.lua_iscfunction(lua.state, index) != 0;
}
/// Returns true if the value at the given `index` is a function (C or Lua)
pub fn isFunction(lua: *Lua, index: i32) bool {
return c.lua_isfunction(lua.state, index);
}
/// Returns true if the value at the given `index` is an integer
pub fn isInteger(lua: *Lua, index: i32) bool {
return c.lua_isinteger(lua.state, index) != 0;
}
/// Returns true if the value at the given `index` is a light userdata
pub fn isLightUserdata(lua: *Lua, index: i32) bool {
return c.lua_islightuserdata(lua.state, index);
}
/// Returns true if the value at the given `index` is nil
pub fn isNil(lua: *Lua, index: i32) bool {
return c.lua_isnil(lua.state, index);
}
/// Returns true if the given `index` is not valid
pub fn isNone(lua: *Lua, index: i32) bool {
return c.lua_isnone(lua.state, index);
}
/// Returns true if the given `index` is not valid or if the value at the `index` is nil
pub fn isNoneOrNil(lua: *Lua, index: i32) bool {
return c.lua_isnoneornil(lua.state, index);
}
/// Returns true if the value at the given `index` is a number
pub fn isNumber(lua: *Lua, index: i32) bool {
return c.lua_isnumber(lua.state, index) != 0;
}
/// Returns true if the value at the given `index` is a string
pub fn isString(lua: *Lua, index: i32) bool {
return c.lua_isstring(lua.state, index) != 0;
}
/// Returns true if the value at the given `index` is a table
pub fn isTable(lua: *Lua, index: i32) bool {
return c.lua_istable(lua.state, index);
}
/// Returns true if the value at the given `index` is a thread
pub fn isThread(lua: *Lua, index: i32) bool {
return c.lua_isthread(lua.state, index);
}
/// Returns true if the value at the given `index` is a userdata (full or light)
pub fn isUserdata(lua: *Lua, index: i32) bool {
return c.lua_isuserdata(lua.state, index) != 0;
}
/// Returns true if the given coroutine can yield
pub fn isYieldable(lua: *Lua) bool {
return c.lua_isyieldable(lua.state) != 0;
}
/// Pushes the length of the value at the given `index` onto the stack
/// Equivalent to the `#` operator in Lua
pub fn len(lua: *Lua, index: i32) void {
c.lua_len(lua.state, index);
}
/// Loads a Lua chunk without running it
pub fn load(lua: *Lua, reader: CReaderFn, data: *anyopaque, chunk_name: [:0]const u8, mode: Mode) !void {
const mode_str = switch (mode) {
.binary => "b",
.text => "t",
.binary_text => "bt",
};
const ret = c.lua_load(lua.state, reader, data, chunk_name, mode_str);
switch (ret) {
StatusCode.ok => return,
StatusCode.err_syntax => return error.Syntax,
StatusCode.err_memory => return error.Memory,
// lua_load runs pcall, so can also return any result of an pcall error
StatusCode.err_runtime => return error.Runtime,
StatusCode.err_error => return error.MsgHandler,
else => unreachable,
}
}
/// Creates a new independent state and returns its main thread
pub fn newState(alloc_fn: AllocFn, data: ?*anyopaque) !Lua {
const state = c.lua_newstate(alloc_fn, data) orelse return error.Memory;
return Lua{ .state = state };
}
/// Creates a new empty table and pushes it onto the stack
/// Equivalent to `Lua.createTable(lua, 0, 0)`
pub fn newTable(lua: *Lua) void {
c.lua_newtable(lua.state);
}
/// Creates a new thread, pushes it on the stack, and returns a `Lua` state that represents the new thread
/// The new thread shares the global environment but has a separate execution stack
pub fn newThread(lua: *Lua) Lua {
const state = c.lua_newthread(lua.state).?;
return .{ .state = state };
}
/// This function creates and pushes a new full userdata onto the stack
/// with `num_uvalue` associated Lua values, plus an associated block of raw memory with `size` bytes
/// Returns the address of the block of memory
pub fn newUserdataUV(lua: *Lua, comptime T: type, new_uvalue: i32) *T {
// safe to .? because this function throws a Lua error on out of memory
// so the returned pointer should never be null
const ptr = c.lua_newuserdatauv(lua.state, @sizeOf(T), new_uvalue).?;
return opaqueCast(T, ptr);
}
/// Pops a key from the stack, and pushes a key-value pair from the table at the given `index`
pub fn next(lua: *Lua, index: i32) bool {
return c.lua_next(lua.state, index) != 0;
}
/// Tries to convert a Lua float into a Lua integer
/// Returns an error if the conversion was unsuccessful
pub fn numberToInteger(n: Number, i: *Integer) !void {
// translate-c failure
// return c.lua_numbertointeger(n, i) != 0;
if (n >= @intToFloat(Number, min_integer) and n < -@intToFloat(Number, min_integer)) {
i.* = @floatToInt(Integer, n);
} else return error.Fail;
}
/// Calls a function (or callable object) in protected mode
pub fn protectedCall(lua: *Lua, num_args: i32, num_results: i32, msg_handler: i32) !void {
// The translate-c version of lua_pcall does not type-check so we must rewrite it
// (macros don't always translate well with translate-c)
const ret = c.lua_pcallk(lua.state, num_args, num_results, msg_handler, 0, null);
switch (ret) {
StatusCode.ok => return,
StatusCode.err_runtime => return error.Runtime,
StatusCode.err_memory => return error.Memory,
StatusCode.err_error => return error.MsgHandler,
else => unreachable,
}
}
/// Behaves exactly like `Lua.protectedCall()` except that it allows the called function to yield
pub fn protectedCallCont(lua: *Lua, num_args: i32, num_results: i32, msg_handler: i32, ctx: Context, k: CContFn) !void {
const ret = c.lua_pcallk(lua.state, num_args, num_results, msg_handler, ctx, k);
switch (ret) {
StatusCode.ok => return,
StatusCode.err_runtime => return error.Runtime,
StatusCode.err_memory => return error.Memory,
StatusCode.err_error => return error.MsgHandler,
else => unreachable,
}
}
/// Pops `n` elements from the top of the stack
pub fn pop(lua: *Lua, n: i32) void {
lua.setTop(-n - 1);
}
/// Pushes a boolean value with value `b` onto the stack
pub fn pushBoolean(lua: *Lua, b: bool) void {
c.lua_pushboolean(lua.state, @boolToInt(b));
}
/// Pushes a new Closure onto the stack
/// `n` tells how many upvalues this function will have
pub fn pushClosure(lua: *Lua, c_fn: CFn, n: i32) void {
c.lua_pushcclosure(lua.state, c_fn, n);
}
/// Pushes a function onto the stack.
/// Equivalent to pushClosure with no upvalues
pub fn pushFunction(lua: *Lua, c_fn: CFn) void {
lua.pushClosure(c_fn, 0);
}
/// Push a formatted string onto the stack
pub fn pushFString(lua: *Lua, fmt: [:0]const u8, args: anytype) void {
_ = lua.pushFStringEx(fmt, args);
}
/// Push a formatted string onto the stack and return a pointer to the string
pub fn pushFStringEx(lua: *Lua, fmt: [:0]const u8, args: anytype) [*:0]const u8 {
const ptr = @call(.{}, c.lua_pushfstring, .{ lua.state, fmt } ++ args);
return @ptrCast([*:0]const u8, ptr);
}
/// Pushes the global environment onto the stack
pub fn pushGlobalTable(lua: *Lua) void {
// lua_pushglobaltable is a macro and c-translate assumes it returns opaque
// so just reimplement the macro here
// c.lua_pushglobaltable(lua.state);
_ = lua.rawGetIndex(registry_index, ridx_globals);
}
/// Pushes an integer with value `n` onto the stack
pub fn pushInteger(lua: *Lua, n: Integer) void {
c.lua_pushinteger(lua.state, n);
}
/// Pushes a light userdata onto the stack
pub fn pushLightUserdata(lua: *Lua, ptr: *anyopaque) void {
c.lua_pushlightuserdata(lua.state, ptr);
}
/// Pushes a slice of bytes onto the stack
pub fn pushBytes(lua: *Lua, bytes: []const u8) void {
_ = lua.pushBytesEx(bytes);
}
/// Pushes the bytes onto the stack. Returns a slice pointing to Lua's internal copy of the string
pub fn pushBytesEx(lua: *Lua, bytes: []const u8) []const u8 {
return c.lua_pushlstring(lua.state, bytes.ptr, bytes.len)[0..bytes.len];
}
/// Pushes a nil value onto the stack
pub fn pushNil(lua: *Lua) void {
c.lua_pushnil(lua.state);
}
/// Pushes a float with value `n` onto the stack
pub fn pushNumber(lua: *Lua, n: Number) void {
c.lua_pushnumber(lua.state, n);
}
/// Pushes a zero-terminated string on to the stack
pub fn pushString(lua: *Lua, str: [:0]const u8) void {
_ = lua.pushStringEx(str);
}
/// Pushes a zero-terminated string onto the stack
/// Lua makes a copy of the string so `str` may be freed immediately after return
/// Returns a pointer to the internal Lua string
pub fn pushStringEx(lua: *Lua, str: [:0]const u8) [:0]const u8 {
return c.lua_pushstring(lua.state, str.ptr).?[0..str.len :0];
}
/// Pushes this thread onto the stack
pub fn pushThread(lua: *Lua) void {
_ = lua.pushThreadEx();
}
/// Pushes this thread onto the stack
/// Returns true if this thread is the main thread of its state
pub fn pushThreadEx(lua: *Lua) bool {
return c.lua_pushthread(lua.state) != 0;
}
/// Pushes a copy of the element at the given index onto the stack
pub fn pushValue(lua: *Lua, index: i32) void {
c.lua_pushvalue(lua.state, index);
}
/// Returns true if the two values in indices `index1` and `index2` are primitively equal
/// Bypasses __eq metamethods
/// Returns false if not equal, or if any index is invalid
pub fn rawEqual(lua: *Lua, index1: i32, index2: i32) bool {
return c.lua_rawequal(lua.state, index1, index2) != 0;
}
/// Similar to `Lua.getTable()` but does a raw access (without metamethods)
pub fn rawGetTable(lua: *Lua, index: i32) LuaType {
return @intToEnum(LuaType, c.lua_rawget(lua.state, index));
}
/// Pushes onto the stack the value t[n], where `t` is the table at the given `index`
/// Returns the `LuaType` of the pushed value
pub fn rawGetIndex(lua: *Lua, index: i32, n: Integer) LuaType {
return @intToEnum(LuaType, c.lua_rawgeti(lua.state, index, n));
}
/// Pushes onto the stack the value t[k] where t is the table at the given `index` and
/// k is the pointer `p` represented as a light userdata
pub fn rawGetPtr(lua: *Lua, index: i32, p: *const anyopaque) LuaType {
return @intToEnum(LuaType, c.lua_rawgetp(lua.state, index, p));
}
/// Returns the raw length of the value at the given index
/// For strings it is the length; for tables it is the result of the `#` operator
/// For userdata it is the size of the block of memory
/// For other values the call returns 0
pub fn rawLen(lua: *Lua, index: i32) Unsigned {
return c.lua_rawlen(lua.state, index);
}
/// Similar to `Lua.setTable()` but does a raw assignment (without metamethods)
pub fn rawSetTable(lua: *Lua, index: i32) void {
c.lua_rawset(lua.state, index);
}
/// Does the equivalent of t[`i`] = v where t is the table at the given `index`
/// and v is the value at the top of the stack
/// Pops the value from the stack. Does not use __newindex metavalue
pub fn rawSetIndex(lua: *Lua, index: i32, i: Integer) void {
c.lua_rawseti(lua.state, index, i);
}
/// Does the equivalent of t[p] = v where t is the table at the given `index`
/// `p` is encoded as a light user data, and v is the value at the top of the stack
/// Pops the value from the stack. Does not use __newindex metavalue
pub fn rawSetPtr(lua: *Lua, index: i32, p: *const anyopaque) void {
c.lua_rawsetp(lua.state, index, p);
}
/// Sets the C function f as the new value of global name
pub fn register(lua: *Lua, name: [:0]const u8, c_fn: CFn) void {
c.lua_register(lua.state, name, c_fn);
}
/// Removes the element at the given valid `index` shifting down elements to fill the gap
pub fn remove(lua: *Lua, index: i32) void {
// translate-c cannot translate this macro correctly
// c.lua_remove(lua.state, index);
lua.rotate(index, -1);
lua.pop(1);
}
/// Moves the top element into the given valid `index` without shifting any elements,
/// then pops the top element
pub fn replace(lua: *Lua, index: i32) void {
// translate-c cannot translate this macro correctly
// c.lua_replace(lua.state, index);
lua.copy(-1, index);
lua.pop(1);
}
/// Resets a thread, cleaning its call stack and closing all pending to-be-closed variables
/// Returns an error if an error occured and leaves an error object on top of the stack
pub fn resetThread(lua: *Lua) !void {
if (c.lua_resetthread(lua.state) != StatusCode.ok) return error.Fail;
}
/// Starts and resumes a coroutine in the given thread
pub fn resumeThread(lua: *Lua, from: ?Lua, num_args: i32, num_results: *i32) !ResumeStatus {
const from_state = if (from) |from_val| from_val.state else null;
const thread_status = c.lua_resume(lua.state, from_state, num_args, num_results);
switch (thread_status) {
StatusCode.err_runtime => return error.Runtime,
StatusCode.err_memory => return error.Memory,
StatusCode.err_error => return error.MsgHandler,
else => return @intToEnum(ResumeStatus, thread_status),
}
}
/// Rotates the stack elements between the valid `index` and the top of the stack
/// The elements are rotated `n` positions in the direction of the top for positive `n`,
/// and `n` positions in the direction of the bottom for negative `n`
pub fn rotate(lua: *Lua, index: i32, n: i32) void {
c.lua_rotate(lua.state, index, n);
}
/// Changes the allocator function of a given state to `alloc_fn` with userdata `data`
pub fn setAllocF(lua: *Lua, alloc_fn: AllocFn, data: ?*anyopaque) void {
c.lua_setallocf(lua.state, alloc_fn, data);
}
/// Does the equivalent to t[`k`] = v where t is the value at the given `index`
/// and v is the value on the top of the stack
pub fn setField(lua: *Lua, index: i32, k: [:0]const u8) void {
c.lua_setfield(lua.state, index, k);
}
/// Pops a value from the stack and sets it as the new value of global `name`
pub fn setGlobal(lua: *Lua, name: [:0]const u8) void {
c.lua_setglobal(lua.state, name);
}
/// Does the equivalent to t[`n`] = v where t is the value at the given `index`
/// and v is the value on the top of the stack. Pops the value from the stack
pub fn setIndex(lua: *Lua, index: i32, n: Integer) void {
c.lua_seti(lua.state, index, n);
}
/// Pops a value from the stack and sets it as the new `n`th user value associated to
/// the full userdata at the given index
/// Returns an error if the userdata does not have that value
pub fn setIndexUserValue(lua: *Lua, index: i32, n: i32) !void {
if (c.lua_setiuservalue(lua.state, index, n) == 0) return error.Fail;
}
/// Pops a table or nil from the stack and sets that value as the new metatable for the
/// value at the given `index`
pub fn setMetatable(lua: *Lua, index: i32) void {
// lua_setmetatable always returns 1 so is safe to ignore
_ = c.lua_setmetatable(lua.state, index);
}
/// Does the equivalent to t[k] = v, where t is the value at the given `index`
/// v is the value on the top of the stack, and k is the value just below the top
pub fn setTable(lua: *Lua, index: i32) void {
c.lua_settable(lua.state, index);
}
/// Sets the top of the stack to `index`
/// If the new top is greater than the old, new elements are filled with nil
/// If `index` is 0 all stack elements are removed
pub fn setTop(lua: *Lua, index: i32) void {
c.lua_settop(lua.state, index);
}
/// Sets the warning function to be used by Lua to emit warnings
/// The `data` parameter sets the value `data` passed to the warning function
pub fn setWarnF(lua: *Lua, warn_fn: CWarnFn, data: ?*anyopaque) void {
c.lua_setwarnf(lua.state, warn_fn, data);
}