Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Question: Is it possible to have an indexer return a callable closure back to Rhai? #951

Open
makspll opened this issue Jan 12, 2025 · 0 comments

Comments

@makspll
Copy link

makspll commented Jan 12, 2025

I am trying to attach an indexer function which performs a dynamic lookup on a function registry (basically bunch of Arc<fn>'s with a specifc signature).

I want to be able to:

let my_dynamic_type = ...
my_dynamic_type.dynamic_function("asd")
my_dynamic_type.dynamic_function2("asd")

given:

#[derive(Clone, Debug, Copy, PartialEq)]
pub struct RhaiStaticReflectReference(pub TypeId);

impl CustomType for RhaiStaticReflectReference {
    fn build(mut builder: rhai::TypeBuilder<Self>) {
        builder
            .with_name(std::any::type_name::<RhaiStaticReflectReference>())
            .with_indexer_get(|self_: &mut Self, index: Dynamic| {
                let world = ThreadWorldContainer.get_world();
                let type_id = self_.0;
                let key: ScriptValue = ScriptValue::from_dynamic(index)?;

                let key = match key.as_string() {
                    // i.e. `dynamic_function` is looked up
                    Ok(name) => match world.lookup_function([type_id], name) {
                        Ok(func) => return ScriptValue::Function(func).into_dynamic(),
                        Err(key) => ScriptValue::String(key),
                    },
                    Err(key) => key,
                };

                let world = ThreadWorldContainer.get_world();
                Err::<_, Box<EvalAltResult>>(
                    InteropError::missing_function(type_id, key.display_with_world(world.clone()))
                        .into(),
                )
            });
    }
}

I know that Dynamic supports FnPtr which you can create via a ScriptFuncDef, however that seems to only be appropriate for actual "script defined" functions

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant