From e41390f8c8ea27c5994d7e466435f1f0761f98fc Mon Sep 17 00:00:00 2001 From: GrayJack Date: Mon, 22 Apr 2024 22:53:09 -0300 Subject: [PATCH] feat: Add `JanetArgs::get_or_else` trait method --- src/types.rs | 28 +++++++++++++++++++++++++++- 1 file changed, 27 insertions(+), 1 deletion(-) diff --git a/src/types.rs b/src/types.rs index 3c6021c8c0..c616480214 100644 --- a/src/types.rs +++ b/src/types.rs @@ -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!() @@ -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(&self, index: usize, op: F) -> T + where + T: TryFrom, + 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`.