rhaiscript / rhai

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

Printing Rust objects from Rhai script #445

Closed curldivergence closed 3 years ago

curldivergence commented 3 years ago

Hello. I have a Rust function that returns a HashMap<String, ObjectID> (ObjectID is my newtype around u64 that implements both Display and Debug). But unfortunately when I'm trying to print this object from a Rhai script like this:

print(`loaded objects: ${scene_objects}`);

I'm getting

std::collections::hash::map::HashMap<alloc::string::String, common::ObjectID>

in my logs instead of the HashMap's contents :( So my question is if there is any way to get the actual map records printed without making a dedicated function for that? Using Debug instead of Display would work for me, too.

Thanks!

schungx commented 3 years ago

https://rhai.rs/book/rust/print-custom.html

This should do it.

Essentially, you define to_string for your custom type.

curldivergence commented 3 years ago

Got it, thank you! On a semi-related note (not to spam with another issue) - do I understand correctly that to be able to index a Vec<T> from Rhai I also need to register a custom function via register_indexer_get?

schungx commented 3 years ago

On a semi-related note (not to spam with another issue) - do I understand correctly that to be able to index a Vec<T> from Rhai I also need to register a custom function via register_indexer_get?

That i s most correct. I'd suggest just registering both a getter and a setter. Remember to bounds-check (meaning you'd need fallible functions). There is even a convenient ErrorArrayBounds error type you can use.

curldivergence commented 3 years ago

I see, thanks a lot for help :)