2 files changed +33
-0
lines changed Original file line number Diff line number Diff line change @@ -356,6 +356,20 @@ pub const Lua = struct {
356
356
c .lua_concat (lua .state , n );
357
357
}
358
358
359
+ /// Calls the C function c_fn in protected mode. The function starts with only one element on its
360
+ /// stack, the userdata given to this function.
361
+ /// See https://www.lua.org/manual/5.1/manual.html#lua_cpcall
362
+ pub fn cProtectedCall (lua : * Lua , c_fn : CFn , userdata : * anyopaque ) ! void {
363
+ const ret = c .lua_cpcall (lua .state , c_fn , userdata );
364
+ switch (ret ) {
365
+ StatusCode .ok = > return ,
366
+ StatusCode .err_runtime = > return error .Runtime ,
367
+ StatusCode .err_memory = > return error .Memory ,
368
+ StatusCode .err_error = > return error .MsgHandler ,
369
+ else = > unreachable ,
370
+ }
371
+ }
372
+
359
373
/// Creates a new empty table and pushes onto the stack
360
374
/// num_arr is a hint for how many elements the table will have as a sequence
361
375
/// num_rec is a hint for how many other elements the table will have
Original file line number Diff line number Diff line change @@ -322,6 +322,25 @@ test "calling a function" {
322
322
try expectEqual (@as (i64 , 42 ), lua .toInteger (1 ));
323
323
}
324
324
325
+ test "calling a function with cProtectedCall" {
326
+ var lua = try Lua .init (testing .allocator );
327
+ defer lua .deinit ();
328
+
329
+ var value : i32 = 1234 ;
330
+
331
+ const testFn = struct {
332
+ fn inner (l : * Lua ) i32 {
333
+ const passedValue = l .toUserdata (i32 , 1 ) catch unreachable ;
334
+ if (passedValue .* != 1234 ) unreachable ;
335
+ return 0 ;
336
+ }
337
+ }.inner ;
338
+
339
+ // cProtectedCall doesn't return values on the stack, so the test just makes
340
+ // sure things work!
341
+ try lua .cProtectedCall (ziglua .wrap (testFn ), & value );
342
+ }
343
+
325
344
test "string buffers" {
326
345
var lua = try Lua .init (testing .allocator );
327
346
defer lua .deinit ();
0 commit comments