Introduce to_int and to_float conersion functions.

This commit is contained in:
Stephen Chung 2020-02-25 15:02:50 +08:00
parent 51abc4a2c1
commit 80a9abada6
2 changed files with 35 additions and 0 deletions

View File

@ -118,6 +118,28 @@ Compiling a script file into AST is also supported:
let ast = Engine::compile_file("hello_world.rhai").unwrap(); 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 # 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. 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.

View File

@ -1064,6 +1064,19 @@ impl Engine {
// directly let ent = engine.fns.entry("[]".to_string()).or_insert_with(Vec::new); // directly let ent = engine.fns.entry("[]".to_string()).or_insert_with(Vec::new);
// (*ent).push(FnType::ExternalFn2(Box::new(idx))); // (*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 // Register print and debug
fn print_debug<T: Debug>(x: T) -> String { fn print_debug<T: Debug>(x: T) -> String {
format!("{:?}", x) format!("{:?}", x)