From 80a9abada60f5f1634e9b4466b2b6cb55043d3eb Mon Sep 17 00:00:00 2001 From: Stephen Chung Date: Tue, 25 Feb 2020 15:02:50 +0800 Subject: [PATCH] Introduce to_int and to_float conersion functions. --- README.md | 22 ++++++++++++++++++++++ src/engine.rs | 13 +++++++++++++ 2 files changed, 35 insertions(+) diff --git a/README.md b/README.md index 29ea9216..495bcf46 100644 --- a/README.md +++ b/README.md @@ -118,6 +118,28 @@ Compiling a script file into AST is also supported: let ast = Engine::compile_file("hello_world.rhai").unwrap(); ``` +# Values and types + +The following primitive types are supported natively: + +* Integer: `i32`, `u32`, `i64` (default), `u64` +* Floating-point: `f32`, `f64` (default) +* Boolean: `bool` +* Array: `rhai::Array` +* Dynamic (i.e. can be anything): `rhai::Dynamic` + +# Value conversions + +All types are treated strictly separate by Rhai, meaning that `i32` and `i64` and `u32` are completely different; you cannot even add them together. + +There is a `to_float` function to convert a supported number to an `f64`, and a `to_int` function to convert a supported number to `i64` and that's about it. For other conversions you can register your own conversion functions. + +```rust +let x = 42; +let y = x * 100.0; // error: cannot multiply i64 with f64 +let y = x.to_float() * 100.0; // works +``` + # Working with functions Rhai's scripting engine is very lightweight. It gets its ability from the functions in your program. To call these functions, you need to register them with the scripting engine. diff --git a/src/engine.rs b/src/engine.rs index ae6220a7..cc18c4e9 100644 --- a/src/engine.rs +++ b/src/engine.rs @@ -1064,6 +1064,19 @@ impl Engine { // directly let ent = engine.fns.entry("[]".to_string()).or_insert_with(Vec::new); // (*ent).push(FnType::ExternalFn2(Box::new(idx))); + // Register conversion functions + engine.register_fn("to_float", |x: i32| x as f64); + engine.register_fn("to_float", |x: u32| x as f64); + engine.register_fn("to_float", |x: i64| x as f64); + engine.register_fn("to_float", |x: u64| x as f64); + engine.register_fn("to_float", |x: f32| x as f64); + + engine.register_fn("to_int", |x: i32| x as i64); + engine.register_fn("to_int", |x: u32| x as i64); + engine.register_fn("to_int", |x: u64| x as i64); + engine.register_fn("to_int", |x: f32| x as i64); + engine.register_fn("to_int", |x: f64| x as i64); + // Register print and debug fn print_debug(x: T) -> String { format!("{:?}", x)