Skip to content

Commit 3ea22a6

Browse files
committed
fix: checkNumeric raises a lua error
1 parent 0ffdfc0 commit 3ea22a6

File tree

1 file changed

+15
-3
lines changed

1 file changed

+15
-3
lines changed

src/lib.zig

Lines changed: 15 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3357,14 +3357,26 @@ pub const Lua = opaque {
33573357

33583358
/// Checks whether the function argument `arg` is a numeric type and converts it to type T
33593359
///
3360-
/// The conversion is done with `@intCast` for numeric types,
3361-
/// so causes an assertion in modes with runtime safety enabled.
3360+
/// Raises a Lua error if the argument is an integer type but std.math.cast fails
33623361
///
33633362
/// * Pops: `0`
33643363
/// * Pushes: `0`
33653364
/// * Errors: `explained in text / on purpose`
33663365
pub fn checkNumeric(lua: *Lua, comptime T: type, arg: i32) T {
3367-
if (@typeInfo(T) == .int) return @intCast(lua.checkInteger(arg));
3366+
if (@typeInfo(T) == .int) return std.math.cast(T, lua.checkNumber(arg)) orelse {
3367+
const error_msg = comptime msg: {
3368+
var buf: [1024]u8 = undefined;
3369+
const info = @typeInfo(T).int;
3370+
const signedness = switch (info.signedness) {
3371+
.unsigned => "u",
3372+
.signed => "i",
3373+
};
3374+
break :msg std.fmt.bufPrintZ(&buf, "Integer argument doesn't fit inside {s}{d} range [{d}, {d}]", .{
3375+
signedness, info.bits, std.math.minInt(T), std.math.maxInt(T),
3376+
}) catch unreachable;
3377+
};
3378+
lua.argError(arg, error_msg);
3379+
};
33683380
return @floatCast(lua.checkNumber(arg));
33693381
}
33703382

0 commit comments

Comments
 (0)