Repository navigation
Expand file tree
/
Copy pathluau.zig
More file actions
740 lines (624 loc) · 29.6 KB
/
Copy pathluau.zig
File metadata and controls
740 lines (624 loc) · 29.6 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
//! A Zig wrapper around the parts of Luau's C API (`luau.h`) that the scripting uses: the state and
//! its stack, tables, userdata, protected calls, the compiler, the sandbox, and the callbacks used
//! for the limits.
//!
//! Luau is built so that errors use `longjmp` (`deps/luau`). A function that raises an error, such
//! as `State.raise` or one of Luau's argument checks, never returns, and Zig `defer`s in the frames
//! it skips don't run. So a C function called from Luau must free what it allocated before calling
//! anything that can raise an error.
const std = @import("std");
const c = @import("luau");
/// A Luau state or thread (`lua_State`).
pub const State = opaque {
fn raw(state: *State) *c.lua_State {
return @ptrCast(state);
}
fn of(raw_state: ?*c.lua_State) *State {
return @ptrCast(raw_state.?);
}
/// Creates a state that allocates through `allocate`, which gets `context`. Returns null if
/// that fails.
pub fn create(allocate: Allocate, context: ?*anyopaque) ?*State {
return @ptrCast(c.lua_newstate(allocate, context) orelse return null);
}
pub fn close(state: *State) void {
c.lua_close(state.raw());
}
/// Opens Luau's standard libraries.
pub fn openLibraries(state: *State) void {
c.luaL_openlibs(state.raw());
}
/// Makes the globals and the standard libraries read-only (`luaL_sandbox`).
pub fn sandbox(state: *State) void {
c.luaL_sandbox(state.raw());
}
/// Creates a thread that shares the state's globals, and pushes it.
pub fn newThread(state: *State) *State {
return of(c.lua_newthread(state.raw()));
}
/// Creates a thread with its own global table, which falls back to the sandboxed globals
/// (`luaL_sandboxthread`), and pushes it.
pub fn newSandboxedThread(state: *State) *State {
const thread = of(c.lua_newthread(state.raw()));
c.luaL_sandboxthread(thread.raw());
return thread;
}
/// The thread at `index`, or null where it isn't one.
pub fn toThread(state: *State, index: i32) ?*State {
const thread = c.lua_tothread(state.raw(), index) orelse return null;
return of(thread);
}
/// The pointer stored with the thread (`lua_getthreaddata`).
pub fn threadData(state: *State, comptime T: type) ?*T {
return @ptrCast(@alignCast(c.lua_getthreaddata(state.raw())));
}
pub fn setThreadData(state: *State, data: ?*anyopaque) void {
c.lua_setthreaddata(state.raw(), data);
}
fn callbacks(state: *State) *c.lua_Callbacks {
return c.lua_callbacks(state.raw());
}
/// The pointer stored with the state's callbacks (`lua_Callbacks.userdata`).
pub fn callbackData(state: *State, comptime T: type) ?*T {
return @ptrCast(@alignCast(state.callbacks().userdata));
}
pub fn setCallbackData(state: *State, data: ?*anyopaque) void {
state.callbacks().userdata = data;
}
/// Sets the interrupt callback, which Luau calls at safe points while a script runs.
/// `collecting` is true when the call comes from the garbage collector, where raising an error
/// isn't allowed.
pub fn setInterrupt(state: *State, comptime run: fn (*State, collecting: bool) void) void {
state.callbacks().interrupt = &struct {
fn call(raw_state: ?*c.lua_State, gc: c_int) callconv(.c) void {
run(of(raw_state), gc >= 0);
}
}.call;
}
/// Sets what runs where an error is raised with no protected call to catch it, just before Luau
/// aborts the process (`lua_Callbacks.panic`).
pub fn setPanic(state: *State, comptime run: fn (*State, Status) void) void {
state.callbacks().panic = &struct {
fn call(raw_state: ?*c.lua_State, code: c_int) callconv(.c) void {
run(of(raw_state), @fromBackingInt(code));
}
}.call;
}
/// Makes new threads, such as coroutines, inherit their parent's thread data.
pub fn inheritThreadData(state: *State) void {
state.callbacks().userthread = &struct {
fn call(parent: ?*c.lua_State, thread: ?*c.lua_State) callconv(.c) void {
const from = parent orelse return;
c.lua_setthreaddata(thread, c.lua_getthreaddata(from));
}
}.call;
}
/// Sets the memory category that the thread's allocations are counted in (`lua_setmemcat`).
pub fn setMemoryCategory(state: *State, category: u8) void {
c.lua_setmemcat(state.raw(), category);
}
/// Runs a full garbage collection.
pub fn collectGarbage(state: *State) void {
_ = c.lua_gc(state.raw(), c.LUA_GCCOLLECT, 0);
}
/// The number of bytes allocated in `category`.
pub fn totalBytes(state: *State, category: u8) usize {
return c.lua_totalbytes(state.raw(), category);
}
// --- Stack ----------------------------------------------------------------------------------
/// Makes room for `count` more values on the stack. Returns false if it can't.
pub fn checkStack(state: *State, count: i32) bool {
return c.lua_checkstack(state.raw(), count) != 0;
}
pub fn top(state: *State) i32 {
return c.lua_gettop(state.raw());
}
pub fn setTop(state: *State, index: i32) void {
c.lua_settop(state.raw(), index);
}
pub fn pop(state: *State, count: i32) void {
c.lua_settop(state.raw(), -count - 1);
}
/// Converts a relative stack index into an absolute one, which stays valid as values are
/// pushed.
pub fn absolute(state: *State, index: i32) i32 {
return c.lua_absindex(state.raw(), index);
}
/// Moves the top value to `index`, shifting the values above it up.
pub fn insert(state: *State, index: i32) void {
c.lua_insert(state.raw(), index);
}
/// Removes the value at `index`, shifting the values above it down.
pub fn remove(state: *State, index: i32) void {
c.lua_remove(state.raw(), index);
}
pub fn pushCopy(state: *State, index: i32) void {
c.lua_pushvalue(state.raw(), index);
}
/// Moves `count` values from the top of `from`'s stack to `to`'s.
pub fn move(from: *State, to: *State, count: i32) void {
c.lua_xmove(from.raw(), to.raw(), count);
}
pub fn typeOf(state: *State, index: i32) Type {
return @fromBackingInt(c.lua_type(state.raw(), index));
}
/// The type name Luau uses in its messages, such as "string".
pub fn typeName(state: *State, index: i32) [:0]const u8 {
return std.mem.span(c.luaL_typename(state.raw(), index));
}
// --- Values ---------------------------------------------------------------------------------
pub fn pushNil(state: *State) void {
c.lua_pushnil(state.raw());
}
pub fn pushBoolean(state: *State, value: bool) void {
c.lua_pushboolean(state.raw(), @intFromBool(value));
}
pub fn pushNumber(state: *State, value: f64) void {
c.lua_pushnumber(state.raw(), value);
}
pub fn pushString(state: *State, value: []const u8) void {
c.lua_pushlstring(state.raw(), value.ptr, value.len);
}
pub fn pushLightUserdata(state: *State, value: *anyopaque) void {
c.lua_pushlightuserdatatagged(state.raw(), value, 0);
}
/// Pushes a C function, with `name` shown in tracebacks.
pub fn pushFunction(state: *State, function: Function, name: [:0]const u8) void {
c.lua_pushcclosurek(state.raw(), function, name, 0, null);
}
/// Pushes a C function that keeps `data`, which it reads with `upvalue`.
pub fn pushClosure(state: *State, function: Function, name: [:0]const u8, data: *anyopaque) void {
state.pushLightUserdata(data);
c.lua_pushcclosurek(state.raw(), function, name, 1, null);
}
/// What the running C function keeps (`pushClosure`).
pub fn upvalue(state: *State, comptime T: type) *T {
return state.toLightUserdata(T, c.LUA_GLOBALSINDEX - 1).?;
}
/// Pushes a vector.
pub fn pushVector(state: *State, value: @Vector(3, f32)) void {
c.lua_pushvector(state.raw(), value[0], value[1], value[2]);
}
/// The vector at `index`, or null if the value isn't a vector.
pub fn toVector(state: *State, index: i32) ?@Vector(3, f32) {
const components = c.lua_tovector(state.raw(), index) orelse return null;
return .{ components[0], components[1], components[2] };
}
pub fn toBoolean(state: *State, index: i32) bool {
return c.lua_toboolean(state.raw(), index) != 0;
}
/// The number at `index`, or null if the value isn't a number.
pub fn toNumber(state: *State, index: i32) ?f64 {
if (state.typeOf(index) != .number) return null;
return c.lua_tonumberx(state.raw(), index, null);
}
/// The string at `index`, or null if the value isn't a string. Numbers aren't converted.
pub fn toString(state: *State, index: i32) ?[]const u8 {
if (state.typeOf(index) != .string) return null;
var len: usize = undefined;
const ptr = c.lua_tolstring(state.raw(), index, &len) orelse return null;
return ptr[0..len];
}
/// The light userdata at `index`, or null if the value isn't light userdata.
pub fn toLightUserdata(state: *State, comptime T: type, index: i32) ?*T {
return @ptrCast(@alignCast(c.lua_tolightuserdata(state.raw(), index) orelse return null));
}
/// Pops `count` values and pushes them concatenated, like `..`.
pub fn concat(state: *State, count: i32) void {
c.lua_concat(state.raw(), count);
}
/// Pushes the value at `index` converted to a string, like `tostring`, and returns it.
pub fn toDisplay(state: *State, index: i32) []const u8 {
var len: usize = undefined;
const ptr = c.luaL_tolstring(state.raw(), index, &len);
return ptr[0..len];
}
// --- Tables ---------------------------------------------------------------------------------
/// Pushes a new table with space preallocated for `array` elements and `fields` fields.
pub fn newTable(state: *State, array: u16, fields: u16) void {
c.lua_createtable(state.raw(), array, fields);
}
/// Pushes `table[key]` for the table at `index`, ignoring metamethods.
pub fn rawGetField(state: *State, index: i32, key: [:0]const u8) Type {
return @fromBackingInt(c.lua_rawgetfield(state.raw(), index, key));
}
/// Pops a value and sets `table[key]` to it for the table at `index`, ignoring metamethods.
pub fn rawSetField(state: *State, index: i32, key: [:0]const u8) void {
c.lua_rawsetfield(state.raw(), index, key);
}
/// Pushes `table[n]` for the table at `index`, ignoring metamethods.
pub fn rawGetIndex(state: *State, index: i32, n: i32) Type {
return @fromBackingInt(c.lua_rawgeti(state.raw(), index, n));
}
/// Pops a value and sets `table[n]` to it for the table at `index`, ignoring metamethods.
pub fn rawSetIndex(state: *State, index: i32, n: i32) void {
c.lua_rawseti(state.raw(), index, n);
}
/// Pops a key and a value, the value on top, and sets `table[key]` to it for the table at
/// `index`, ignoring metamethods.
pub fn rawSet(state: *State, index: i32) void {
c.lua_rawset(state.raw(), index);
}
/// Pushes `table[key]` for the table at `index` and the key on top, which it pops, ignoring
/// metamethods.
pub fn rawGet(state: *State, index: i32) Type {
return @fromBackingInt(c.lua_rawget(state.raw(), index));
}
/// Pops a table and makes it the metatable of the table at `index`.
pub fn setMetatable(state: *State, index: i32) void {
_ = c.lua_setmetatable(state.raw(), index);
}
/// What scripts' `getmetatable` gives for a value whose metatable is locked (`lockMetatable`),
/// in the words Roblox uses for its own objects.
pub const locked_metatable = "The metatable is locked";
/// Hides the metatable on top of the stack from scripts: `getmetatable` gives
/// `locked_metatable` in its place, so a script can't call its metamethods by hand.
pub fn lockMetatable(state: *State) void {
state.pushString(locked_metatable);
state.rawSetField(-2, "__metatable");
}
/// Pushes a copy of the table at `index`, with the same metatable (`lua_clonetable`).
pub fn cloneTable(state: *State, index: i32) void {
c.lua_clonetable(state.raw(), index);
}
/// Pops a key and pushes the next key and value of the table at `index` (`lua_next`). Returns
/// false after the last one.
pub fn next(state: *State, index: i32) bool {
return c.lua_next(state.raw(), index) != 0;
}
pub fn setReadonly(state: *State, index: i32, readonly: bool) void {
c.lua_setreadonly(state.raw(), index, @intFromBool(readonly));
}
/// Pops a value and sets the global `name` to it.
pub fn setGlobal(state: *State, name: [:0]const u8) void {
c.lua_setfield(state.raw(), c.LUA_GLOBALSINDEX, name);
}
/// Pushes the global `name`.
pub fn getGlobal(state: *State, name: [:0]const u8) Type {
return @fromBackingInt(c.lua_getfield(state.raw(), c.LUA_GLOBALSINDEX, name));
}
// --- Userdata -------------------------------------------------------------------------------
/// Pushes new userdata holding a `T`, with the metatable registered for `tag`
/// (`setUserdataMetatable`). The `T` is uninitialized.
pub fn newUserdata(state: *State, comptime T: type, tag: Tag) *T {
const raw_data = c.lua_newuserdatataggedwithmetatable(state.raw(), @sizeOf(T), tag);
return @ptrCast(@alignCast(raw_data));
}
/// The `T` in the userdata at `index`, or null if the value isn't userdata with `tag`.
pub fn toUserdata(state: *State, comptime T: type, index: i32, tag: Tag) ?*T {
return @ptrCast(@alignCast(c.lua_touserdatatagged(state.raw(), index, tag) orelse return null));
}
/// The `T` in the userdata at `index`, as a metamethod takes its first argument. Raises an
/// error saying `what` was expected if the value isn't userdata with `tag`.
pub fn checkUserdata(state: *State, comptime T: type, index: i32, tag: Tag, what: []const u8) *T {
return state.toUserdata(T, index, tag) orelse state.raise("expected {s}, got {s}", .{ what, state.typeName(index) });
}
/// Pops a table and registers it as the metatable for userdata with `tag`.
pub fn setUserdataMetatable(state: *State, tag: Tag) void {
c.lua_setuserdatametatable(state.raw(), tag);
}
/// Registers the metatable of userdata with `tag`: its `methods`, and `type_name` for Luau's
/// `typeof`. Scripts can neither change the metatable nor reach it (`lockMetatable`).
pub fn registerUserdata(state: *State, tag: Tag, type_name: []const u8, methods: []const Method) void {
state.newTable(0, @intCast(methods.len + 2));
for (methods) |method| {
state.pushFunction(method[1], method[0]);
state.rawSetField(-2, method[0]);
}
state.pushString(type_name);
state.rawSetField(-2, "__type");
state.lockMetatable();
state.setReadonly(-1, true);
state.setUserdataMetatable(tag);
}
// --- References -----------------------------------------------------------------------------
/// Creates a reference to the value at `index`, which keeps it from being collected until
/// `unref`.
pub fn ref(state: *State, index: i32) Ref {
return @fromBackingInt(c.lua_ref(state.raw(), index));
}
pub fn unref(state: *State, reference: Ref) void {
_ = c.lua_unref(state.raw(), @backingInt(reference));
}
/// Pushes the referenced value.
pub fn pushRef(state: *State, reference: Ref) Type {
return @fromBackingInt(c.lua_rawgeti(state.raw(), c.LUA_REGISTRYINDEX, @backingInt(reference)));
}
// --- Calls ----------------------------------------------------------------------------------
/// Calls the function below the `arguments` on the stack in protected mode. On success it
/// leaves `results` results, or all of them for `all_results`; on failure it leaves the error
/// message with a traceback. It pushes a new `traceback` function as the error handler, which
/// takes memory before the call is protected. That suits a call made while a script runs, whose
/// own protected call catches running out of memory, and tests; the engine's calls into scripts
/// use `protectedCallWith`.
pub fn protectedCall(state: *State, arguments: i32, results: i32) Status {
state.pushFunction(traceback, "traceback");
return state.protectedCallTopHandler(arguments, results);
}
/// `protectedCall`, with `handler` as the error handler: a reference to `traceback`, made
/// beforehand, so that nothing takes memory before the call is protected. Needs a free place
/// on the stack.
pub fn protectedCallWith(state: *State, arguments: i32, results: i32, handler: Ref) Status {
_ = state.pushRef(handler);
return state.protectedCallTopHandler(arguments, results);
}
/// Calls the function below the `arguments` with the error handler on top of the stack, which
/// it moves below the function and takes away again.
fn protectedCallTopHandler(state: *State, arguments: i32, results: i32) Status {
const base = state.top() - 1 - arguments;
state.insert(base);
const status: Status = @fromBackingInt(c.lua_pcall(state.raw(), arguments, results, base));
c.lua_remove(state.raw(), base);
return status;
}
/// The error handler of the protected calls (`protectedCall`, `protectedCallWith`): adds a
/// traceback to the message.
pub fn traceback(raw_state: ?*c.lua_State) callconv(.c) c_int {
const L = raw_state.?;
const message = c.lua_tolstring(L, 1, null);
c.luaL_traceback(L, L, message, 1);
return 1;
}
/// Like `protectedCall`, but leaves the error as it was raised, without a traceback.
pub fn protectedCallBare(state: *State, arguments: i32, results: i32) Status {
return @fromBackingInt(c.lua_pcall(state.raw(), arguments, results, 0));
}
/// Calls the C function `function` in protected mode with `context` as its argument
/// (`lua_cpcall`). Its results are discarded.
pub fn protectedCallC(state: *State, function: Function, context: ?*anyopaque) Status {
return @fromBackingInt(c.lua_cpcall(state.raw(), function, context));
}
/// Raises an error with a formatted message, prefixed with the script's file and line. Never
/// returns. Messages longer than `max_message` are cut off.
pub fn raise(state: *State, comptime format: []const u8, arguments: anytype) noreturn {
var buffer: [max_message]u8 = undefined;
const message = std.mem.print(&buffer, format, arguments) catch buffer[0..];
c.luaL_where(state.raw(), 1);
state.pushString(message);
c.lua_concat(state.raw(), 2);
c.lua_error(state.raw());
}
/// Raises the value on top of the stack as an error. Never returns.
pub fn raiseTop(state: *State) noreturn {
c.lua_error(state.raw());
}
// --- Loading --------------------------------------------------------------------------------
/// Loads compiled `bytecode` as a function named `chunk` and pushes it. If loading fails,
/// pushes the error message instead. The function uses the thread's globals. Loading can raise
/// an out-of-memory error, so call it in protected mode (`protectedCallC`).
pub fn load(state: *State, chunk: [:0]const u8, bytecode: []const u8) Status {
return if (c.luau_load(state.raw(), chunk, bytecode.ptr, bytecode.len, 0) == 0) .ok else .syntax_error;
}
};
/// The `results` of `State.protectedCall` that keeps every result (`LUA_MULTRET`).
pub const all_results = c.LUA_MULTRET;
/// The longest error message `State.raise` produces.
pub const max_message = 512;
/// Compiles Luau source code to bytecode, which must be freed with `Bytecode.free`. Returns null if
/// out of memory. If the source has errors, the bytecode encodes the error, which `State.load`
/// reports.
pub fn compile(source: []const u8) ?Bytecode {
var options = std.mem.zeroes(c.lua_CompileOptions);
options.optimizationLevel = optimization_level;
options.debugLevel = debug_level;
var len: usize = undefined;
const ptr = c.luau_compile(source.ptr, source.len, &options, &len) orelse return null;
return .{ .bytes = ptr[0..len] };
}
/// Bytecode allocated by the compiler with C's allocator.
pub const Bytecode = struct {
bytes: []const u8,
pub fn free(bytecode: Bytecode) void {
std.c.free(@constCast(bytecode.bytes.ptr));
}
};
/// Luau's baseline optimization, which keeps tracebacks complete.
const optimization_level = 1;
/// Keep line numbers and function names for errors and tracebacks.
const debug_level = 1;
/// A C function that Luau can call.
pub const Function = *const fn (?*c.lua_State) callconv(.c) c_int;
/// A metamethod of a userdata's metatable, such as `__index`, and its function.
pub const Method = struct { [:0]const u8, Function };
/// Wraps a Zig function as a C function for Luau. `run` returns the number of results it pushed.
pub fn wrap(comptime run: fn (*State) i32) Function {
return &struct {
fn call(raw_state: ?*c.lua_State) callconv(.c) c_int {
return run(State.of(raw_state));
}
}.call;
}
/// Luau's allocator callback (`lua_Alloc`): resizes `ptr` from `old` to `new` bytes, frees it when
/// `new` is 0, and allocates when `ptr` is null.
pub const Allocate = *const fn (context: ?*anyopaque, ptr: ?*anyopaque, old: usize, new: usize) callconv(.c) ?*anyopaque;
/// The type of a Luau value (`lua_type`).
pub const Type = enum(c_int) {
none = c.LUA_TNONE,
nil = c.LUA_TNIL,
boolean = c.LUA_TBOOLEAN,
light_userdata = c.LUA_TLIGHTUSERDATA,
number = c.LUA_TNUMBER,
integer = c.LUA_TINTEGER,
vector = c.LUA_TVECTOR,
string = c.LUA_TSTRING,
table = c.LUA_TTABLE,
function = c.LUA_TFUNCTION,
userdata = c.LUA_TUSERDATA,
thread = c.LUA_TTHREAD,
buffer = c.LUA_TBUFFER,
class = c.LUA_TCLASS,
_,
};
/// The result of a call or a load.
pub const Status = enum(c_int) {
ok = c.LUA_OK,
yield = c.LUA_YIELD,
runtime_error = c.LUA_ERRRUN,
syntax_error = c.LUA_ERRSYNTAX,
memory_error = c.LUA_ERRMEM,
handler_error = c.LUA_ERRERR,
@"break" = c.LUA_BREAK,
_,
};
/// A reference created by `State.ref`.
pub const Ref = enum(c_int) {
_,
};
/// A userdata tag, which selects the userdata's metatable. Luau allows tags below
/// `c.LUA_UTAG_LIMIT`.
pub const Tag = std.math.IntFittingRange(0, c.LUA_UTAG_LIMIT - 1);
test "a script runs, and errors report the line" {
const state = State.create(testing.allocate, null).?;
defer state.close();
state.openLibraries();
state.sandbox();
const thread = state.newSandboxedThread();
const good = compile("local x = 40 + 2; return x").?;
defer good.free();
try std.testing.expectEqual(Status.ok, thread.load("=good", good.bytes));
try std.testing.expectEqual(Status.ok, thread.protectedCall(0, 1));
try std.testing.expectEqual(42, thread.toNumber(-1).?);
thread.pop(1);
const bad = compile("local t = nil\nreturn t.field").?;
defer bad.free();
try std.testing.expectEqual(Status.ok, thread.load("=bad", bad.bytes));
try std.testing.expectEqual(Status.runtime_error, thread.protectedCall(0, 1));
const message = thread.toString(-1).?;
try std.testing.expect(std.mem.startsWith(u8, message, "bad:2: attempt to index nil"));
}
test "a protected call with its handler made beforehand takes no memory before it is protected" {
const state = State.create(testing.allocate, null).?;
defer state.close();
state.openLibraries();
state.pushFunction(State.traceback, "traceback");
const handler = state.ref(-1);
state.pop(1);
const nothing = compile("return").?;
defer nothing.free();
try std.testing.expectEqual(Status.ok, state.load("=nothing", nothing.bytes));
var allocations: usize = 0;
testing.countAllocations(state, &allocations);
try std.testing.expectEqual(Status.ok, state.protectedCallWith(0, 0, handler));
try std.testing.expectEqual(0, allocations);
// A new handler for each call takes memory first.
try std.testing.expectEqual(Status.ok, state.load("=nothing", nothing.bytes));
try std.testing.expectEqual(Status.ok, state.protectedCall(0, 0));
try std.testing.expect(allocations > 0);
// The handler adds the traceback all the same.
const failing = compile("local function deeper() error('broke') end\ndeeper()").?;
defer failing.free();
try std.testing.expectEqual(Status.ok, state.load("=failing", failing.bytes));
try std.testing.expectEqual(Status.runtime_error, state.protectedCallWith(0, 0, handler));
const message = state.toString(-1).?;
try std.testing.expect(std.mem.startsWith(u8, message, "failing:1: broke"));
try std.testing.expect(std.mem.find(u8, message, "deeper") != null);
}
test "a syntax error is reported when loading" {
const state = State.create(testing.allocate, null).?;
defer state.close();
const broken = compile("local = 1").?;
defer broken.free();
try std.testing.expectEqual(Status.syntax_error, state.load("=broken", broken.bytes));
try std.testing.expect(std.mem.startsWith(u8, state.toString(-1).?, "broken:1:"));
}
test "every script of the example mods compiles" {
const state = State.create(testing.allocate, null).?;
defer state.close();
inline for (@import("example_scripts").scripts) |path| {
const bytecode = compile(@embedFile(path)).?;
defer bytecode.free();
if (state.load("=" ++ path, bytecode.bytes) != .ok) {
std.debug.print("{s}\n", .{state.toString(-1).?});
return error.TestUnexpectedResult;
}
state.pop(1);
}
}
test "vectors and closures" {
const state = State.create(testing.allocate, null).?;
defer state.close();
state.pushVector(.{ 1, 2, 3 });
try std.testing.expectEqual(Type.vector, state.typeOf(-1));
try std.testing.expectEqual(@Vector(3, f32){ 1, 2, 3 }, state.toVector(-1).?);
try std.testing.expectEqual(null, state.toVector(-2));
state.pop(1);
var kept: u32 = 7;
const reads = struct {
fn reads(called: *State) i32 {
called.pushNumber(@floatFromInt(called.upvalue(u32).*));
return 1;
}
}.reads;
state.pushClosure(wrap(reads), "reads", &kept);
try std.testing.expectEqual(Status.ok, state.protectedCall(0, 1));
try std.testing.expectEqual(7, state.toNumber(-1).?);
}
test "the sandbox makes the standard libraries read-only" {
const state = State.create(testing.allocate, null).?;
defer state.close();
state.openLibraries();
state.sandbox();
const thread = state.newSandboxedThread();
const changing = compile("math.pi = 3").?;
defer changing.free();
try std.testing.expectEqual(Status.ok, thread.load("=changing", changing.bytes));
try std.testing.expectEqual(Status.runtime_error, thread.protectedCall(0, 0));
try std.testing.expect(std.mem.find(u8, thread.toString(-1).?, "readonly") != null);
}
test "scripts can't reach a userdata's metatable, and its metamethods check their argument" {
const state = State.create(testing.allocate, null).?;
defer state.close();
state.openLibraries();
const tag: Tag = 1;
const sample = struct {
fn index(called: *State) i32 {
called.pushNumber(called.checkUserdata(f64, 1, tag, "a sample").*);
return 1;
}
};
state.registerUserdata(tag, "sample", &.{.{ "__index", wrap(sample.index) }});
state.newUserdata(f64, tag).* = 7;
state.setGlobal("sample");
state.sandbox();
const thread = state.newSandboxedThread();
testing.exposeMetatables(thread);
const source = compile(
\\assert(sample.anything == 7)
\\assert(getmetatable(sample) == "The metatable is locked")
\\local ok, message = pcall(rawgetmetatable(sample).__index, nil, "anything")
\\assert(not ok and string.find(message, "expected a sample, got nil", 1, true))
).?;
defer source.free();
try std.testing.expectEqual(Status.ok, thread.load("=locked", source.bytes));
try std.testing.expectEqual(Status.ok, thread.protectedCall(0, 0));
}
pub const testing = struct {
/// An allocator for states in tests, using C's allocator.
pub fn allocate(_: ?*anyopaque, ptr: ?*anyopaque, _: usize, new: usize) callconv(.c) ?*anyopaque {
if (new == 0) {
std.c.free(ptr);
return null;
}
return std.c.realloc(ptr, new);
}
/// Counts each block `state` allocates from now on in `count` (`lua_Callbacks.onallocate`),
/// which the state's callback data then points to.
pub fn countAllocations(state: *State, count: *usize) void {
state.setCallbackData(count);
state.callbacks().onallocate = &struct {
fn call(raw_state: ?*c.lua_State, _: ?*anyopaque, _: usize, _: usize, _: u8, _: c_int, _: c_int) callconv(.c) void {
State.of(raw_state).callbackData(usize).?.* += 1;
}
}.call;
}
/// Gives the scripts on `thread` `rawgetmetatable`, which reaches a locked metatable
/// (`State.lockMetatable`), so that tests can call its metamethods by hand as no mod can.
pub fn exposeMetatables(thread: *State) void {
thread.pushFunction(wrap(rawGetmetatable), "rawgetmetatable");
thread.setGlobal("rawgetmetatable");
}
fn rawGetmetatable(state: *State) i32 {
if (c.lua_getmetatable(state.raw(), 1) == 0) state.pushNil();
return 1;
}
};