Skip to content
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 36 additions & 0 deletions src/lib.zig
Original file line number Diff line number Diff line change
Expand Up @@ -2594,6 +2594,17 @@ pub const Lua = opaque {
c.lua_toclose(@ptrCast(lua), index);
}

/// Converts the Lua value at the given `index` to a numeric type;
/// if T is an integer type, the Lua value is converted to an integer.
///
/// * Pops: `0`
/// * Pushes: `0`
/// * Errors: `error.IntegerCastFailed` if `T` is an integer type and the value at index doesn't fit
pub fn toNumeric(lua: *Lua, comptime T: type, index: i32) !T {
if (@typeInfo(T) == .int) return std.math.cast(T, try lua.toInteger(index)) orelse error.IntegerCastFailed;
Comment thread
robbielyman marked this conversation as resolved.
Outdated
return @floatCast(try lua.toNumber(index));
}

/// Converts the Lua value at the given `index` to a signed integer
/// The Lua value must be an integer, or a number, or a string convertible to an integer
/// Returns an error if the conversion failed
Expand Down Expand Up @@ -3342,6 +3353,31 @@ pub const Lua = opaque {
c.luaL_checkany(@ptrCast(lua), arg);
}

/// Checks whether the function argument `arg` is a numeric type and converts it to type T
///
/// Raises a Lua error if the argument is an integer type but std.math.cast fails
///
/// * Pops: `0`
/// * Pushes: `0`
/// * Errors: `explained in text / on purpose`
pub fn checkNumeric(lua: *Lua, comptime T: type, arg: i32) T {
if (@typeInfo(T) == .int) return std.math.cast(T, lua.checkNumber(arg)) orelse {
Comment thread
robbielyman marked this conversation as resolved.
Outdated
const error_msg = comptime msg: {
var buf: [1024]u8 = undefined;
const info = @typeInfo(T).int;
const signedness = switch (info.signedness) {
.unsigned => "u",
.signed => "i",
};
break :msg std.fmt.bufPrintZ(&buf, "Integer argument doesn't fit inside {s}{d} range [{d}, {d}]", .{
signedness, info.bits, std.math.minInt(T), std.math.maxInt(T),
}) catch unreachable;
};
lua.argError(arg, error_msg);
};
return @floatCast(lua.checkNumber(arg));
}

/// Checks whether the function argument `arg` is a number and returns this number cast to an i32
///
/// Not available in Lua 5.3 and 5.4
Expand Down
10 changes: 10 additions & 0 deletions src/tests.zig
Original file line number Diff line number Diff line change
Expand Up @@ -3055,3 +3055,13 @@ test "error union for CFn" {
try expectEqualStrings("MissingInteger", try lua.toString(-1));
};
}

test "pushNumeric and toNumeric" {
const lua: *Lua = try .init(testing.allocator);
Comment thread
robbielyman marked this conversation as resolved.
defer lua.deinit();

const num: u32 = 100;
lua.pushInteger(num);
const pull = lua.toNumeric(u32, lua.getTop());
try std.testing.expectEqual(num, pull);
}
Loading