Add evaluate expressions.
This commit is contained in:
32
README.md
32
README.md
@@ -183,10 +183,6 @@ let result = engine.eval_file::<i64>("hello_world.rhai".into())?; // 'eval
|
||||
To repeatedly evaluate a script, _compile_ it first into an AST (abstract syntax tree) form:
|
||||
|
||||
```rust
|
||||
use rhai::Engine;
|
||||
|
||||
let mut engine = Engine::new();
|
||||
|
||||
// Compile to an AST and store it for later evaluations
|
||||
let ast = engine.compile("40 + 2")?;
|
||||
|
||||
@@ -200,20 +196,12 @@ for _ in 0..42 {
|
||||
Compiling a script file is also supported:
|
||||
|
||||
```rust
|
||||
use rhai::Engine;
|
||||
|
||||
let mut engine = Engine::new();
|
||||
|
||||
let ast = engine.compile_file("hello_world.rhai".into())?;
|
||||
```
|
||||
|
||||
Rhai also allows working _backwards_ from the other direction - i.e. calling a Rhai-scripted function from Rust - via `call_fn`:
|
||||
|
||||
```rust
|
||||
use rhai::Engine;
|
||||
|
||||
let mut engine = Engine::new();
|
||||
|
||||
// Define a function in a script and load it into the Engine.
|
||||
// Pass true to 'retain_functions' otherwise these functions will be cleared at the end of consume()
|
||||
engine.consume(true,
|
||||
@@ -241,6 +229,26 @@ let result: i64 = engine.call_fn("hello", 123_i64)?
|
||||
// ^^^^^^^ calls 'hello' with one parameter (no need for tuple)
|
||||
```
|
||||
|
||||
Evaluate expressions only
|
||||
-------------------------
|
||||
|
||||
Sometimes a use case does not require a full-blown scripting _language_, but only needs to evaluate _expressions_.
|
||||
In these cases, use the `compile_expression` and `eval_expression` methods or their `_with_scope` variants.
|
||||
|
||||
```rust
|
||||
let result = engine.eval_expression::<i64>("2 + (10 + 10) * 2")?;
|
||||
```
|
||||
|
||||
When evaluation _expressions_, no control-flow statement (e.g. `if`, `while`, `for`) is not supported and will be
|
||||
parse errors when encountered - not even variable assignments.
|
||||
|
||||
```rust
|
||||
// The following are all syntax errors because the script is not an expression.
|
||||
engine.eval_expression::<()>("x = 42")?;
|
||||
let ast = engine.compile_expression("let x = 42")?;
|
||||
let result = engine.eval_expression_with_scope::<i64>(&mut scope, "if x { 42 } else { 123 }")?;
|
||||
```
|
||||
|
||||
Values and types
|
||||
----------------
|
||||
|
||||
|
Reference in New Issue
Block a user