rhaiscript / rhai

Rhai - An embedded scripting language for Rust.
https://crates.io/crates/rhai
Apache License 2.0
3.81k stars 179 forks source link

Register function with custom type as parameter not work #690

Closed n0b0dyCN closed 1 year ago

n0b0dyCN commented 1 year ago

main.rs

use rhai::Engine;

#[derive(Debug)]
pub struct TestStruct {
    field: i64,
}

impl Clone for TestStruct {
    fn clone(&self) -> Self {
        println!("value cloned");
        Self {
            field: self.field.clone(),
        }
    }
}

impl TestStruct {
    fn new() -> Self {
        Self { field: 1 }
    }
}

pub fn print_test(x: &TestStruct) {
    println!("print_test: field={}", x.field);
}

fn main() {
    let mut engine = Engine::new();
    engine
        .register_type::<TestStruct>()
        .register_fn("new_ts", TestStruct::new)
        .register_fn("print_test", print_test);
    engine
        .run(
            "
        let x = new_ts();                   // calls 'TestStruct::new'
        print_test(x);                      // print test
    ",
        )
        .unwrap();
}

Got error:

thread 'main' panicked at 'called `Result::unwrap()` on an `Err` value: ErrorFunctionNotFound("print_test (rhai_test::TestStruct)", 3:9)', src/main.rs:38:8

Is there anything wrong when registering the function?

schungx commented 1 year ago

Reference parameters are not supported.

https://rhai.rs/book/rust/methods.html#admonition-no-support-for-references

n0b0dyCN commented 1 year ago

Reference parameters are not supported.

https://rhai.rs/book/rust/methods.html#admonition-no-support-for-references

When reading the document, I thought only class methods have this constraint. Thanks for your explain.