Skip to content

Commit 2beee53

Browse files
committedFeb 16, 2023
feat: add cProtectedCall to lua 5.1 api
This function was missed. It doesn't seem horribly useful, but might as well support it.
1 parent edf6386 commit 2beee53

File tree

2 files changed

+33
-0
lines changed

2 files changed

+33
-0
lines changed
 

‎src/ziglua-5.1/lib.zig

+14
Original file line numberDiff line numberDiff line change
@@ -356,6 +356,20 @@ pub const Lua = struct {
356356
c.lua_concat(lua.state, n);
357357
}
358358

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+
359373
/// Creates a new empty table and pushes onto the stack
360374
/// num_arr is a hint for how many elements the table will have as a sequence
361375
/// num_rec is a hint for how many other elements the table will have

‎src/ziglua-5.1/tests.zig

+19
Original file line numberDiff line numberDiff line change
@@ -322,6 +322,25 @@ test "calling a function" {
322322
try expectEqual(@as(i64, 42), lua.toInteger(1));
323323
}
324324

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+
325344
test "string buffers" {
326345
var lua = try Lua.init(testing.allocator);
327346
defer lua.deinit();

0 commit comments

Comments
 (0)
Failed to load comments.