types: add proper Function support

This commit is contained in:
numzero 2025-04-19 14:57:32 +03:00
parent c77e0703f9
commit cdc54f54cb

View File

@ -37,6 +37,7 @@ impl_from!(Number, i32);
impl_from!(String, String); impl_from!(String, String);
impl_from!(String, &str); impl_from!(String, &str);
impl_from!(Table, Table); impl_from!(Table, Table);
impl_from!(Function, Function);
pub type Value = Option<ValueInner>; pub type Value = Option<ValueInner>;
@ -79,7 +80,7 @@ impl Table {
#[derive(Clone)] #[derive(Clone)]
pub struct Function { pub struct Function {
name: &'static str, name: String,
inner: Rc<dyn Fn(&[Value]) -> Value>, inner: Rc<dyn Fn(&[Value]) -> Value>,
} }
@ -104,6 +105,12 @@ impl Hash for Function {
} }
impl Function { impl Function {
pub fn new(name: Option<String>, f: impl Fn(&[Value]) -> Value + 'static) -> Self {
let inner = Rc::new(f);
let name = name.unwrap_or_else(|| format!("function {:?}", inner.as_ref() as *const _));
Self { name, inner }
}
pub fn call(&self, args: &[Value]) -> Value { pub fn call(&self, args: &[Value]) -> Value {
(self.inner)(args) (self.inner)(args)
} }