Add evaluate expressions.

This commit is contained in:
Stephen Chung
2020-03-22 21:03:58 +08:00
parent b6320c0eef
commit 1b4bcbcfdf
5 changed files with 313 additions and 77 deletions

View File

@@ -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
----------------