Skip to content

Commit

Permalink
feat: add cProtectedCall to lua 5.1 api
Browse files Browse the repository at this point in the history
This function was missed. It doesn't seem horribly useful, but might as
well support it.
  • Loading branch information
natecraddock committed Feb 16, 2023
1 parent edf6386 commit 2beee53
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 0 deletions.
14 changes: 14 additions & 0 deletions src/ziglua-5.1/lib.zig
Original file line number Diff line number Diff line change
Expand Up @@ -356,6 +356,20 @@ pub const Lua = struct {
c.lua_concat(lua.state, n);
}

/// Calls the C function c_fn in protected mode. The function starts with only one element on its
/// stack, the userdata given to this function.
/// 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(lua.state, c_fn, userdata);
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,
}
}

/// 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
Expand Down
19 changes: 19 additions & 0 deletions src/ziglua-5.1/tests.zig
Original file line number Diff line number Diff line change
Expand Up @@ -322,6 +322,25 @@ test "calling a function" {
try expectEqual(@as(i64, 42), lua.toInteger(1));
}

test "calling a function with cProtectedCall" {
var lua = try Lua.init(testing.allocator);
defer lua.deinit();

var value: i32 = 1234;

const testFn = struct {
fn inner(l: *Lua) i32 {
const passedValue = l.toUserdata(i32, 1) catch unreachable;
if (passedValue.* != 1234) unreachable;
return 0;
}
}.inner;

// cProtectedCall doesn't return values on the stack, so the test just makes
// sure things work!
try lua.cProtectedCall(ziglua.wrap(testFn), &value);
}

test "string buffers" {
var lua = try Lua.init(testing.allocator);
defer lua.deinit();
Expand Down

0 comments on commit 2beee53

Please sign in to comment.