Skip to content

Commit

Permalink
feat: Add JanetArgs::get_or_else trait method
Browse files Browse the repository at this point in the history
  • Loading branch information
GrayJack committed Apr 23, 2024
1 parent b43b2d4 commit e41390f
Showing 1 changed file with 27 additions and 1 deletion.
28 changes: 27 additions & 1 deletion src/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1875,7 +1875,7 @@ pub trait JanetArgs {
/// // defaults to the given value.
/// #[janet_fn(arity(range(0, 1)))]
/// fn my_func(args: &mut [Janet]) -> Janet {
/// let my_flag = args.get_or_default(0);
/// let my_flag: i32 = args.get_or_default(0);
///
/// // Rest of the function
/// todo!()
Expand All @@ -1890,6 +1890,32 @@ pub trait JanetArgs {
.unwrap_or_default()
}

/// Get the argument at the `index` position and convert to `T`, if that fails,
/// computes the value from a closure.
///
/// # Examples
///
/// ```
/// use janetrs::{janet_fn, Janet, JanetArgs};
///
/// // Lets say it's a function that if receives an argument, if is not the wanted type, it
/// // defaults to the given value.
/// #[janet_fn(arity(range(0, 1)))]
/// fn my_func(args: &mut [Janet]) -> Janet {
/// let my_flag: i32 = args.get_or_else(0, |_| 10);
///
/// // Rest of the function
/// todo!()
/// }
/// ```
fn get_or_else<T, F>(&self, index: usize, op: F) -> T
where
T: TryFrom<Janet>,
F: FnOnce(T::Error) -> T,
{
self.try_get(index).unwrap_or_else(op)
}

/// Get the argument at the `index` position, if it's Janet nil, returns the `default`
/// value, but janet panics if the the value is different than nil and fail to convert
/// to `T`.
Expand Down

0 comments on commit e41390f

Please sign in to comment.