Skip to content

Commit

Permalink
docs: Add docs on splitting yolk.rhai into multiple files
Browse files Browse the repository at this point in the history
  • Loading branch information
elkowar committed Jan 26, 2025
1 parent 57a2f3f commit 060ffec
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 0 deletions.
32 changes: 32 additions & 0 deletions docs/src/yolk_rhai.md
Original file line number Diff line number Diff line change
Expand Up @@ -102,3 +102,35 @@ To look at the contents of those variables or try out your logic, you can always
```bash
$ yolk eval 'print(SYSTEM)'
```

## Splitting up into multiple files

Rhai allows you to import other files into your scripts.
For example, let's say you want to keep your color theme definition in a separate file.
Simply create a new `colors.rhai` file next to your `yolk.rhai`, and make sure to explicitly declare exported variables as `export`:

```rust
export let gruvbox = #{
background: "#282828",
foreground: "#ebdbb2",
};

fn some_function() {
print("hi")
}
```

Note that functions are exported by default.

Now, in your `yolk.rhai`, import this script, giving the module an explict name:

```rs
import "colors" as colors;
```

Now you can refer to anything exported from that file as `colors::thing`, i.e.:

```rs
let theme = colors::gruvbox;
colors::some_function();
```
7 changes: 7 additions & 0 deletions src/script/stdlib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -110,10 +110,17 @@ pub fn utils_module() -> Module {
.in_global_namespace()
.set_into_module(&mut module, rhai_color_hex_to_rgb);

FuncRegistration::new("color_hex_to_rgb")
.with_comments(["/// Convert a hex color string to an RGB map."])
.with_params_info(["hex_string: &str", "Result<Map>"])
.in_global_namespace()
.set_into_module(&mut module, rhai_color_hex_to_rgb);

let color_hex_to_rgb_str = |hex_string: String| -> Result<String, Box<EvalAltResult>> {
let (r, g, b, _) = color_hex_to_rgb(&hex_string)?;
Ok(format!("rgb({r}, {g}, {b})"))
};

FuncRegistration::new("color_hex_to_rgb_str")
.with_comments(["/// Convert a hex color string to an RGB string."])
.with_params_info(["hex_string: &str", "Result<String>"])
Expand Down

0 comments on commit 060ffec

Please sign in to comment.