Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update wrap functions to handle error unions #47

Closed
natecraddock opened this issue Jan 15, 2024 · 3 comments
Closed

Update wrap functions to handle error unions #47

natecraddock opened this issue Jan 15, 2024 · 3 comments

Comments

@natecraddock
Copy link
Owner

It would sometimes be useful to use try in a wrapped zig function and have that propagate as a Lua error. This should be pretty easy to do with comptime

@VisenDev
Copy link
Contributor

My implementation of autoPushFunction automatically does this.

                if (@typeInfo(info.Fn.return_type.?) == .ErrorUnion) {
                    const result = @call(.auto, function, parameters) catch |err| {
                        lua.raiseErrorStr(@errorName(err), .{});
                    };
                    lua.pushAny(result);
                } else {
                    const result = @call(.auto, function, parameters);
                    lua.pushAny(result);
                }

@natecraddock
Copy link
Owner Author

Thanks for the example! Really helpful.

I got this to work with ziglua.wrap, but it requires annotating the function with anyerror

    const inner = struct {
        fn inner(l: *Lua) anyerror!i32 {
            const allocator = l.allocator();

            const num = try l.toInteger(1);

            // Use the allocator
            const nums = try allocator.alloc(i32, @intCast(num));
            defer allocator.free(nums);

            // Do something pointless to use the slice
            var sum: i32 = 0;
            for (nums, 0..) |*n, i| n.* = @intCast(i);
            for (nums) |n| sum += n;

            l.pushInteger(sum);
            return 1;
        }
    }.inner;

    lua.pushFunction(ziglua.wrap(inner));

Probably not the end of the world, but I would prefer it if the function could be left as ! or also explicitly listing the possible errors

@natecraddock
Copy link
Owner Author

Solved it 🚀

natecraddock added a commit that referenced this issue Oct 12, 2024
Any ziglua.wrap supported function that has a *Lua parameter now allows
using error unions in the return type. Any Zig errors that are returned
will be raised as a Lua error.

Closes #47
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants