rhailib/src/derive/README.md
2025-06-25 03:22:03 +02:00

79 lines
1.9 KiB
Markdown

# Rhai Derive Macros
This crate provides procedural macros to simplify the integration of Rust types with the Rhai scripting engine.
## `RhaiApi` Derive Macro
The `RhaiApi` macro automatically generates a Rhai module with a fluent, builder-style API for your Rust structs. This allows you to create and modify your structs in Rhai scripts using chained method calls.
### How It Works
When you derive `RhaiApi` on a struct, the macro generates:
1. A new Rust module named `{struct_name}_rhai_dsl`.
2. A Rhai `export_module` within that module named `generated_rhai_module`.
3. A `new_{struct_name}()` function to create a new instance of your struct.
4. Setter functions for each field in your struct, allowing for method chaining.
5. An `id()` function to retrieve the object's ID.
### Example
**Rust Struct Definition:**
```rust
use derive::RhaiApi;
#[derive(RhaiApi, Clone)]
pub struct Product {
pub id: i64,
pub name: String,
pub price: f64,
}
```
**Generated Rhai API Usage:**
```rhai
// Import the generated module
import product_rhai_dsl::generated_rhai_module as product_api;
// Use the fluent API to build a new product
let my_product = product_api::new_product()
.id(1)
.name("Awesome Gadget")
.price(99.99);
print(my_product.id()); // prints 1
```
## `FromVec` Derive Macro
The `FromVec` macro is a utility for tuple structs that contain a single field. It implements the `From<T>` trait, where `T` is the inner type, allowing for seamless conversions.
### Example
**Rust Struct Definition:**
```rust
use derive::FromVec;
#[derive(FromVec)]
pub struct MyVec(Vec<u8>);
```
**Usage:**
```rust
let data = vec![1, 2, 3];
let my_vec = MyVec::from(data);
```
## Usage
To use these macros in your project, add this crate as a dependency in your `Cargo.toml` file:
```toml
[dependencies]
derive = { path = "../path/to/rhailib/src/derive" }
```