rhai/README.md

872 lines
22 KiB
Markdown
Raw Normal View History

2020-03-03 10:28:38 +01:00
# Rhai - Embedded Scripting for Rust
2016-02-29 22:43:45 +01:00
2016-04-14 03:52:12 +02:00
Rhai is an embedded scripting language for Rust that gives you a safe and easy way to add scripting to your applications.
2016-03-02 20:53:12 +01:00
2016-03-03 15:59:53 +01:00
Rhai's current feature set:
2016-03-03 16:10:08 +01:00
* Easy integration with Rust functions and data types
2016-03-03 15:59:53 +01:00
* Fairly efficient (1 mil iterations in 0.75 sec on my 5 year old laptop)
2016-03-04 14:08:34 +01:00
* Low compile-time overhead (~0.6 sec debug/~3 sec release for script runner app)
2020-03-03 10:28:38 +01:00
* Easy-to-use language similar to JS+Rust
2016-03-03 15:59:53 +01:00
* Support for overloaded functions
* No additional dependencies
2020-03-05 13:28:03 +01:00
**Note:** Currently, the version is 0.10.1, so the language and API's may change before they stabilize.
2016-03-14 16:31:24 +01:00
## Installation
2020-02-25 04:23:46 +01:00
You can install Rhai using crates by adding this line to your dependencies:
2016-03-14 16:31:24 +01:00
2017-12-11 07:32:12 +01:00
```toml
2016-03-14 16:31:24 +01:00
[dependencies]
rhai = "0.10.1"
2016-03-14 16:31:24 +01:00
```
2020-03-02 08:20:29 +01:00
or simply:
```toml
[dependencies]
rhai = "*"
```
to use the latest version.
Beware that in order to use pre-releases (alpha and beta) you need to specify the exact version in your `Cargo.toml`.
2020-02-25 04:23:46 +01:00
## Optional Features
### `debug_msgs`
Print debug messages to stdout (using `println!`) related to function registrations and function calls.
### `no_stdlib`
Exclude the standard library of utility functions in the build, and only include the minimum necessary functionalities.
2016-03-14 16:31:24 +01:00
## Related
2016-03-03 16:00:29 +01:00
2016-03-04 14:13:57 +01:00
Other cool projects to check out:
2020-02-25 08:01:50 +01:00
2016-03-04 14:13:57 +01:00
* [ChaiScript](http://chaiscript.com/) - A strong inspiration for Rhai. An embedded scripting language for C++ that I helped created many moons ago, now being lead by my cousin.
* You can also check out the list of [scripting languages for Rust](https://github.com/rust-unofficial/awesome-rust#scripting) on [awesome-rust](https://github.com/rust-unofficial/awesome-rust)
2016-03-04 14:13:57 +01:00
## Examples
2020-02-25 08:01:50 +01:00
The repository contains several examples in the `examples` folder:
2020-02-25 08:01:50 +01:00
* `arrays_and_structs` demonstrates registering a new type to Rhai and the usage of arrays on it
* `custom_types_and_methods` shows how to register a type and methods for it
* `hello` simple example that evaluates an expression and prints the result
* `reuse_scope` evaluates two pieces of code in separate runs, but using a common scope
* `rhai_runner` runs each filename passed to it as a Rhai script
* `simple_fn` shows how to register a Rust function to a Rhai engine
* `repl` a simple REPL, see source code for what it can do at the moment
Examples can be run with the following command:
2020-02-25 08:01:50 +01:00
```bash
cargo run --example name
```
## Example Scripts
2020-02-25 08:01:50 +01:00
We also have a few examples scripts that showcase Rhai's features, all stored in the `scripts` folder:
2020-02-25 08:01:50 +01:00
* `array.rhai` - arrays in Rhai
* `assignment.rhai` - variable declarations
* `comments.rhai` - just comments
* `for1.rhai` - for loops
* `function_decl1.rhai` - a function without parameters
* `function_decl2.rhai` - a function with two parameters
* `function_decl3.rhai` - a function with many parameters
* `if1.rhai` - if example
* `loop.rhai` - endless loop in Rhai, this example emulates a do..while cycle
* `op1.rhai` - just a simple addition
* `op2.rhai` - simple addition and multiplication
* `op3.rhai` - change evaluation order with parenthesis
* `speed_test.rhai` - a simple program to measure the speed of Rhai's interpreter
* `string.rhai`- string operations
* `while.rhai` - while loop
To run the scripts, you can either make your own tiny program, or make use of the `rhai_runner`
example program:
2020-02-25 08:01:50 +01:00
```bash
cargo run --example rhai_runner scripts/any_script.rhai
```
2016-03-31 16:01:58 +02:00
# Hello world
2016-04-14 03:52:12 +02:00
To get going with Rhai, you create an instance of the scripting engine and then run eval.
2016-02-29 22:43:45 +01:00
2017-11-04 11:18:56 +01:00
```rust
2016-03-03 17:07:45 +01:00
use rhai::Engine;
2016-03-02 20:40:07 +01:00
2016-03-03 17:07:45 +01:00
fn main() {
let mut engine = Engine::new();
2016-04-14 03:52:12 +02:00
if let Ok(result) = engine.eval::<i64>("40 + 2") {
2016-03-26 21:45:24 +01:00
println!("Answer: {}", result); // prints 42
2016-03-03 17:07:45 +01:00
}
2016-03-02 20:40:07 +01:00
}
```
2016-03-31 16:01:58 +02:00
2016-03-31 16:06:39 +02:00
You can also evaluate a script file:
2017-11-04 11:18:56 +01:00
```rust
2016-04-14 03:52:12 +02:00
if let Ok(result) = engine.eval_file::<i64>("hello_world.rhai") { ... }
2016-03-31 16:06:39 +02:00
```
2020-02-25 04:08:40 +01:00
If you want to repeatedly evaluate a script, you can compile it first into an AST form:
```rust
2020-02-25 08:01:50 +01:00
// Compile to an AST and store it for later evaluations
let ast = Engine::compile("40 + 2").unwrap();
2020-02-25 04:08:40 +01:00
for _ in 0..42 {
if let Ok(result) = engine.eval_ast::<i64>(&ast) {
println!("Answer: {}", result); // prints 42
}
}
```
Compiling a script file into AST is also supported:
```rust
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)
2020-03-01 06:30:22 +01:00
* Character: `char`
* 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.
2020-03-03 10:28:38 +01:00
There is also a `type_of` function to detect the type of a value.
```rust
let x = 42;
let y = x * 100.0; // error: cannot multiply i64 with f64
let y = x.to_float() * 100.0; // works
2020-03-01 06:30:22 +01:00
let z = y.to_int() + x; // works
let c = 'X'; // character
2020-03-03 10:28:38 +01:00
print("c is '" + c + "' and its code is " + c.to_int()); // prints "c is 'X' and its code is 88"
// Use 'type_of' to get the type of variables
type_of(c) == "char";
type_of(x) == "i64";
y.type_of() == "f64";
if z.type_of() == "string" {
do_something_with_strong(z);
}
```
2016-03-31 16:01:58 +02:00
# Working with functions
2016-03-02 20:53:12 +01:00
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.
2017-11-04 11:18:56 +01:00
```rust
2020-02-25 08:01:50 +01:00
use rhai::{Dynamic, Engine, RegisterFn};
2016-03-03 17:07:45 +01:00
2020-02-25 03:43:13 +01:00
// Normal function
2016-04-14 03:52:12 +02:00
fn add(x: i64, y: i64) -> i64 {
2016-03-02 20:53:12 +01:00
x + y
}
2020-02-25 08:01:50 +01:00
// Function that returns a Dynamic value
fn get_an_any() -> Dynamic {
2020-02-25 03:43:13 +01:00
Box::new(42_i64)
}
2016-03-02 20:53:12 +01:00
fn main() {
let mut engine = Engine::new();
2016-03-26 21:42:54 +01:00
engine.register_fn("add", add);
2016-04-14 03:52:12 +02:00
if let Ok(result) = engine.eval::<i64>("add(40, 2)") {
2016-03-26 21:45:24 +01:00
println!("Answer: {}", result); // prints 42
2016-03-02 20:53:12 +01:00
}
2020-02-25 03:43:13 +01:00
2020-02-25 08:01:50 +01:00
// Functions that return Dynamic values must use register_dynamic_fn()
engine.register_dynamic_fn("get_an_any", get_an_any);
2020-02-25 03:43:13 +01:00
if let Ok(result) = engine.eval::<i64>("get_an_any()") {
println!("Answer: {}", result); // prints 42
}
2016-03-02 20:53:12 +01:00
}
```
2016-03-02 20:40:07 +01:00
2020-03-03 10:28:38 +01:00
To return a `Dynamic` value, simply `Box` it and return it.
2020-03-02 10:04:56 +01:00
```rust
fn decide(yes_no: bool) -> Dynamic {
if yes_no {
Box::new(42_i64)
} else {
Box::new("hello world!".to_string()) // remember &str is not supported
}
}
```
2016-03-31 16:01:58 +02:00
# Working with generic functions
2016-03-02 20:53:12 +01:00
Generic functions can be used in Rhai, but you'll need to register separate instances for each concrete type:
2017-11-04 11:18:56 +01:00
```rust
2016-03-03 17:07:45 +01:00
use std::fmt::Display;
use rhai::{Engine, RegisterFn};
2016-03-03 17:07:45 +01:00
2016-03-02 20:53:12 +01:00
fn showit<T: Display>(x: &mut T) -> () {
println!("{}", x)
}
fn main() {
let mut engine = Engine::new();
2016-04-14 03:52:12 +02:00
engine.register_fn("print", showit as fn(x: &mut i64)->());
2016-03-26 21:42:54 +01:00
engine.register_fn("print", showit as fn(x: &mut bool)->());
engine.register_fn("print", showit as fn(x: &mut String)->());
2016-03-02 20:53:12 +01:00
}
```
2016-03-04 14:10:53 +01:00
You can also see in this example how you can register multiple functions (or in this case multiple instances of the same function) to the same name in script. This gives you a way to overload functions and call the correct one, based on the types of the arguments, from your script.
2016-03-03 16:14:11 +01:00
2020-03-02 08:20:29 +01:00
# Override built-in functions
2020-03-02 10:04:56 +01:00
Any similarly-named function defined in a script overrides any built-in function.
2020-03-02 08:20:29 +01:00
```rust
// Override the built-in function 'to_int'
fn to_int(num) {
print("Ha! Gotcha!" + num);
}
print(to_int(123)); // what will happen?
```
2016-03-31 16:01:58 +02:00
# Custom types and methods
2016-03-02 20:40:07 +01:00
2016-03-02 21:08:35 +01:00
Here's an more complete example of working with Rust. First the example, then we'll break it into parts:
2016-03-02 20:53:12 +01:00
2017-11-04 11:18:56 +01:00
```rust
use rhai::{Engine, RegisterFn};
2016-03-03 17:07:45 +01:00
2016-03-10 22:48:56 +01:00
#[derive(Clone)]
2016-03-02 20:40:07 +01:00
struct TestStruct {
2016-04-14 03:52:12 +02:00
x: i64
2016-03-02 20:40:07 +01:00
}
impl TestStruct {
fn update(&mut self) {
self.x += 1000;
}
fn new() -> TestStruct {
TestStruct { x: 1 }
}
}
2016-03-03 17:07:45 +01:00
fn main() {
let mut engine = Engine::new();
2016-03-02 20:40:07 +01:00
2016-03-03 17:07:45 +01:00
engine.register_type::<TestStruct>();
2016-03-02 20:40:07 +01:00
2016-03-26 21:42:54 +01:00
engine.register_fn("update", TestStruct::update);
engine.register_fn("new_ts", TestStruct::new);
2016-03-02 20:40:07 +01:00
2017-10-02 18:46:35 +02:00
if let Ok(result) = engine.eval::<TestStruct>("let x = new_ts(); x.update(); x") {
2016-03-03 17:07:45 +01:00
println!("result: {}", result.x); // prints 1001
}
2016-03-02 20:40:07 +01:00
}
```
First, for each type we use with the engine, we need to be able to Clone. This allows the engine to pass by value and still keep its own state.
2017-11-04 11:18:56 +01:00
```rust
2016-03-10 22:48:56 +01:00
#[derive(Clone)]
2016-03-02 20:40:07 +01:00
struct TestStruct {
2016-04-14 03:52:12 +02:00
x: i64
2016-03-02 20:40:07 +01:00
}
```
Next, we create a few methods that we'll later use in our scripts. Notice that we register our custom type with the engine.
2020-02-25 08:01:50 +01:00
2017-11-04 11:18:56 +01:00
```rust
2016-03-02 20:40:07 +01:00
impl TestStruct {
fn update(&mut self) {
self.x += 1000;
}
fn new() -> TestStruct {
TestStruct { x: 1 }
}
}
let mut engine = Engine::new();
engine.register_type::<TestStruct>();
```
To use methods and functions with the engine, we need to register them. There are some convenience functions to help with this. Below I register update and new with the engine.
2016-03-02 20:53:12 +01:00
*Note: the engine follows the convention that methods use a &mut first parameter so that invoking methods can update the value in memory.*
2016-03-02 20:40:07 +01:00
2017-11-04 11:18:56 +01:00
```rust
2016-03-26 21:42:54 +01:00
engine.register_fn("update", TestStruct::update);
engine.register_fn("new_ts", TestStruct::new);
2016-03-02 20:40:07 +01:00
```
Finally, we call our script. The script can see the function and method we registered earlier. We need to get the result back out from script land just as before, this time casting to our custom struct type.
2020-02-25 08:01:50 +01:00
2017-11-04 11:18:56 +01:00
```rust
2017-10-02 18:46:35 +02:00
if let Ok(result) = engine.eval::<TestStruct>("let x = new_ts(); x.update(); x") {
2016-03-02 20:40:07 +01:00
println!("result: {}", result.x); // prints 1001
}
```
2016-03-04 14:27:06 +01:00
2020-02-25 08:01:50 +01:00
In fact, any function with a first argument (either by copy or via a `&mut` reference) can be used as a method-call on that type because internally they are the same thing: methods on a type is implemented as a functions taking an first argument.
```rust
fn foo(ts: &mut TestStruct) -> i64 {
ts.x
}
engine.register_fn("foo", foo);
if let Ok(result) = engine.eval::<i64>("let x = new_ts(); x.foo()") {
println!("result: {}", result); // prints 1
}
```
2020-03-03 10:28:38 +01:00
`type_of` works fine with custom types and returns the name of the type:
```rust
let x = new_ts();
print(x.type_of()); // prints "foo::bar::TestStruct"
```
2020-02-25 08:01:50 +01:00
2020-03-04 15:00:01 +01:00
If you use `register_type_with_name` to register the custom type with a special pretty-print name, `type_of` will return that instead.
2016-03-31 16:01:58 +02:00
# Getters and setters
2016-03-10 22:25:03 +01:00
2016-04-14 03:52:12 +02:00
Similarly, you can work with members of your custom types. This works by registering a 'get' or a 'set' function for working with your struct.
2016-03-10 22:25:03 +01:00
For example:
2017-11-04 11:18:56 +01:00
```rust
2016-03-10 22:25:03 +01:00
#[derive(Clone)]
struct TestStruct {
2016-04-14 03:52:12 +02:00
x: i64
2016-03-10 22:25:03 +01:00
}
impl TestStruct {
2016-04-14 03:52:12 +02:00
fn get_x(&mut self) -> i64 {
2016-03-10 22:25:03 +01:00
self.x
}
2016-04-14 03:52:12 +02:00
fn set_x(&mut self, new_x: i64) {
2016-03-10 22:25:03 +01:00
self.x = new_x;
}
fn new() -> TestStruct {
TestStruct { x: 1 }
}
}
let mut engine = Engine::new();
engine.register_type::<TestStruct>();
2016-03-26 21:42:54 +01:00
engine.register_get_set("x", TestStruct::get_x, TestStruct::set_x);
engine.register_fn("new_ts", TestStruct::new);
2016-03-10 22:25:03 +01:00
2017-10-02 18:46:35 +02:00
if let Ok(result) = engine.eval::<i64>("let a = new_ts(); a.x = 500; a.x") {
2016-03-10 22:25:03 +01:00
println!("result: {}", result);
}
```
2020-03-01 06:30:22 +01:00
### WARNING: Gotcha's with Getters
When you _get_ a property, the value is cloned. Any update to it downstream will **NOT** be reflected back to the custom type.
This can introduce subtle bugs. For example:
```rust
fn change(s) {
s = 42;
}
let a = new_ts();
a.x = 500;
a.x.change(); // Only a COPY of 'a.x' is changed. 'a.x' is NOT changed.
a.x == 500;
```
2020-03-03 08:20:20 +01:00
# Initializing and maintaining state
2016-03-04 14:27:06 +01:00
By default, Rhai treats each engine invocation as a fresh one, persisting only the functions that have been defined but no top-level state. This gives each one a fairly clean starting place. Sometimes, though, you want to continue using the same top-level state from one invocation to the next.
2020-03-03 08:20:20 +01:00
In this example, we first create a state with a few initialized variables, then thread the same state through multiple invocations:
2016-03-04 14:27:06 +01:00
2017-11-04 11:18:56 +01:00
```rust
2016-03-04 14:27:06 +01:00
use rhai::{Engine, Scope};
fn main() {
let mut engine = Engine::new();
2020-03-03 08:20:20 +01:00
// First create the state
2019-09-18 12:21:07 +02:00
let mut scope = Scope::new();
2016-03-04 14:27:06 +01:00
2020-03-03 08:20:20 +01:00
// Then push some initialized variables into the state
// NOTE: Remember the default numbers used by Rhai are i64 and f64.
// Better stick to them or it gets hard to work with other variables in the script.
scope.push("y".into(), 42_i64);
scope.push("z".into(), 999_i64);
// First invocation
engine.eval_with_scope::<()>(&mut scope, r"
let x = 4 + 5 - y + z;
y = 1;
").expect("y and z not found?");
2016-03-04 14:27:06 +01:00
2020-03-03 08:20:20 +01:00
// Second invocation using the same state
2016-04-14 03:52:12 +02:00
if let Ok(result) = engine.eval_with_scope::<i64>(&mut scope, "x") {
2020-03-03 08:20:20 +01:00
println!("result: {}", result); // should print 966
2016-03-04 14:27:06 +01:00
}
2020-03-03 08:20:20 +01:00
// Variable y is changed in the script
assert_eq!(scope.get_value::<i64>("y").unwrap(), 1);
2016-03-04 14:27:06 +01:00
}
```
2016-03-10 22:25:03 +01:00
2016-03-31 16:03:03 +02:00
# Rhai Language guide
2016-03-31 15:59:54 +02:00
## Variables
2017-11-04 11:18:56 +01:00
```rust
2017-10-02 18:46:35 +02:00
let x = 3;
2016-03-31 15:59:54 +02:00
```
2020-03-02 05:08:03 +01:00
## Numeric operators
2016-03-31 15:59:54 +02:00
2017-11-04 11:18:56 +01:00
```rust
2017-10-02 18:46:35 +02:00
let x = (1 + 2) * (6 - 4) / 2;
2016-03-31 15:59:54 +02:00
```
## Comparison operators
You can compare most values of the same data type. If you compare two values of _different_ data types, the result is always `false`.
```rust
42 == 42; // true
42 > 42; // false
"hello" > "foo"; // true
"42" == 42; // false
42 == 42.0; // false - i64 is different from f64
```
2020-03-02 05:08:03 +01:00
## Boolean operators
Double boolean operators `&&` and `||` _short-circuit_, meaning that the second operand will not be evaluated if the first one already proves the condition wrong.
Single boolean operators `&` and `|` always evaluate both operands.
```rust
this() || that(); // that() is not evaluated if this() is true
this() && that(); // that() is not evaluated if this() is false
this() | that(); // both this() and that() are evaluated
this() & that(); // both this() and that() are evaluated
```
2016-03-31 15:59:54 +02:00
## If
2020-02-25 08:01:50 +01:00
2017-11-04 11:18:56 +01:00
```rust
2016-04-14 03:52:12 +02:00
if true {
2020-03-02 10:04:56 +01:00
print("It's true!");
} else if true {
print("It's true again!");
} else {
2016-03-31 15:59:54 +02:00
print("It's false!");
}
```
## While
2020-02-25 08:01:50 +01:00
2017-11-04 11:18:56 +01:00
```rust
2017-10-02 18:46:35 +02:00
let x = 10;
2020-03-02 10:04:56 +01:00
2016-04-14 03:52:12 +02:00
while x > 0 {
2016-03-31 15:59:54 +02:00
print(x);
2020-03-02 10:04:56 +01:00
if x == 5 { break; }
2016-03-31 15:59:54 +02:00
x = x - 1;
}
```
## Loop
2020-02-25 08:01:50 +01:00
```rust
let x = 10;
loop {
print(x);
x = x - 1;
if x == 0 { break; }
}
```
2016-03-31 15:59:54 +02:00
## Functions
Rhai supports defining functions in script:
2017-11-04 11:18:56 +01:00
```rust
2016-03-31 15:59:54 +02:00
fn add(x, y) {
return x + y;
}
print(add(2, 3));
2016-03-31 15:59:54 +02:00
```
Just like in Rust, you can also use an implicit return.
2017-11-04 11:18:56 +01:00
```rust
2016-03-31 15:59:54 +02:00
fn add(x, y) {
x + y
}
print(add(2, 3));
2016-03-31 15:59:54 +02:00
```
2020-02-25 03:43:13 +01:00
2020-03-03 10:28:38 +01:00
Remember that functions defined in script always take `Dynamic` arguments (i.e. the arguments can be of any type).
Arguments are passed by value, so all functions are _pure_ (i.e. they never modify their arguments).
Furthermore, functions can only be defined at the top level, never inside a block or another function.
```rust
// Top level is OK
fn add(x, y) {
x + y
}
// The following will not compile
fn do_addition(x) {
fn add_y(n) { // functions cannot be defined inside another function
n + y
}
add_y(x)
}
```
2020-03-03 11:15:20 +01:00
## Return
```rust
return;
return 123 + 456;
```
## Errors and Exceptions
```rust
if error != "" {
2020-03-05 13:28:03 +01:00
throw error; // 'throw' takes a string to form the exception text
2020-03-03 11:15:20 +01:00
}
throw; // no exception text
```
All of `Engine`'s evaluation/consuming methods return `Result<T, rhai::EvalAltResult>` with `EvalAltResult` holding error information.
Exceptions thrown via `throw` in the script can be captured by matching `Err(EvalAltResult::ErrorRuntime(reason, position))` with the exception text captured by the `reason` parameter.
```rust
let result = engine.eval::<i64>(&mut scope, r#"
let x = 42;
if x > 0 {
throw x + " is too large!";
}
"#);
println!(result); // prints "Runtime error: 42 is too large! (line 5, position 15)"
```
2016-04-14 03:52:12 +02:00
## Arrays
2016-03-31 15:59:54 +02:00
You can create arrays of values, and then access them with numeric indices.
2020-02-25 09:23:59 +01:00
The following functions (defined in the standard library but excluded if you use the `no_stdlib` feature) operate on arrays:
2020-02-25 09:23:59 +01:00
* `push` - inserts an element at the end
* `pop` - removes the last element and returns it (() if empty)
* `shift` - removes the first element and returns it (() if empty)
* `len` - returns the number of elements
* `pad` - pads the array with an element until a specified length
* `clear` - empties the array
2020-02-25 09:23:59 +01:00
* `truncate` - cuts off the array at exactly a specified length (discarding all subsequent elements)
2016-03-31 15:59:54 +02:00
2017-11-04 11:18:56 +01:00
```rust
2020-02-25 03:43:13 +01:00
let y = [1, 2, 3]; // 3 elements
y[1] = 42;
print(y[1]); // prints 42
2020-03-04 15:00:01 +01:00
ts.list = y; // arrays can be assigned completely (by value copy)
2020-03-05 13:28:03 +01:00
let foo = ts.list[1];
2020-03-04 15:00:01 +01:00
foo == 42;
2020-03-05 13:28:03 +01:00
let foo = [1, 2, 3][0];
foo == 1;
fn abc() { [42, 43, 44] }
let foo = abc()[0];
foo == 42;
let foo = y[0];
foo == 1;
2020-03-01 06:30:22 +01:00
2020-02-25 03:43:13 +01:00
y.push(4); // 4 elements
y.push(5); // 5 elements
2016-03-31 15:59:54 +02:00
2020-02-25 03:43:13 +01:00
print(y.len()); // prints 5
let first = y.shift(); // remove the first element, 4 elements remaining
first == 1;
let last = y.pop(); // remove the last element, 3 elements remaining
last == 5;
2020-02-25 09:23:59 +01:00
print(y.len()); // prints 3
y.pad(10, "hello"); // pad the array up to 10 elements
print(y.len()); // prints 10
y.truncate(5); // truncate the array to 5 elements
print(y.len()); // prints 5
y.clear(); // empty the array
print(y.len()); // prints 0
2020-02-25 03:43:13 +01:00
```
2020-02-25 09:23:59 +01:00
`push` and `pad` are only defined for standard built-in types. If you want to use them with
2020-02-25 03:43:13 +01:00
your own custom type, you need to define a specific override:
2020-02-25 08:01:50 +01:00
2020-02-25 03:43:13 +01:00
```rust
2020-03-02 08:20:29 +01:00
engine.register_fn("push",
|list: &mut Array, item: MyType| list.push(Box::new(item))
);
2020-02-25 03:43:13 +01:00
```
2020-03-03 10:28:38 +01:00
The type of a Rhai array is `rhai::Array`. `type_of()` returns `"array"`.
2020-02-25 08:01:50 +01:00
## For loops
2020-02-25 03:43:13 +01:00
```rust
let array = [1, 3, 5, 7, 9, 42];
for x in array {
print(x);
if x == 42 { break; }
}
// The range function allows iterating from first..last-1
for x in range(0,50) {
print(x);
if x == 42 { break; }
}
2016-03-31 15:59:54 +02:00
```
## Members and methods
2017-11-04 11:18:56 +01:00
```rust
2017-10-02 18:46:35 +02:00
let a = new_ts();
2016-03-31 15:59:54 +02:00
a.x = 500;
a.update();
```
2020-03-03 14:39:25 +01:00
## Numbers
```rust
let x = 123; // i64
let x = 123.4; // f64
let x = 123_456_789; // separators can be put anywhere inside the number
let x = 0x12abcd; // i64 in hex
let x = 0o777; // i64 in oct
let x = 0b1010_1111; // i64 in binary
```
Conversion functions (defined in the standard library but excluded if you use the `no_stdlib` feature):
2020-03-03 14:39:25 +01:00
* `to_int` - converts an `f32` or `f64` to `i64`
* `to_float` - converts an integer type to `f64`
2016-04-14 03:52:12 +02:00
## Strings and Chars
2017-11-04 11:18:56 +01:00
```rust
2017-10-02 18:46:35 +02:00
let name = "Bob";
let middle_initial = 'C';
2020-03-03 14:39:25 +01:00
let last = "Davis";
2020-02-25 03:43:13 +01:00
let full_name = name + " " + middle_initial + ". " + last;
full_name == "Bob C. Davis";
// String building with different types (not available if 'no_stdlib' features is used)
2020-02-25 03:43:13 +01:00
let age = 42;
2020-03-01 06:30:22 +01:00
let record = full_name + ": age " + age;
record == "Bob C. Davis: age 42";
// Strings can be indexed to get a character
let c = record[4];
c == 'C';
2020-03-04 15:00:01 +01:00
ts.s = record;
2020-03-05 13:28:03 +01:00
let c = ts.s[4];
2020-03-04 15:00:01 +01:00
c == 'C';
2020-03-05 13:28:03 +01:00
let c = "foo"[0];
c == 'f';
let c = ("foo" + "bar")[5];
c == 'r';
2020-03-01 06:30:22 +01:00
2020-03-03 14:39:25 +01:00
// Escape sequences in strings
record += " \u2764\n"; // escape sequence of '❤' in Unicode
2020-03-05 13:28:03 +01:00
record == "Bob C. Davis: age 42 ❤\n"; // '\n' = new-line
2020-03-03 14:39:25 +01:00
2020-03-01 06:30:22 +01:00
// Unlike Rust, Rhai strings can be modified
2020-03-03 14:39:25 +01:00
record[4] = '\x58'; // 0x58 = 'X'
record == "Bob X. Davis: age 42 ❤\n";
2020-03-01 06:30:22 +01:00
```
The following standard functions (defined in the standard library but excluded if you use the `no_stdlib` feature) operate on strings:
2020-03-01 06:30:22 +01:00
* `len` - returns the number of characters (not number of bytes) in the string
* `pad` - pads the string with an character until a specified number of characters
* `clear` - empties the string
2020-03-01 06:30:22 +01:00
* `truncate` - cuts off the string at exactly a specified number of characters
* `contains` - checks if a certain character or sub-string occurs in the string
2020-03-01 06:30:22 +01:00
* `replace` - replaces a substring with another
* `trim` - trims the string
2020-03-01 06:30:22 +01:00
```rust
let full_name == " Bob C. Davis ";
full_name.len() == 14;
full_name.trim();
2020-03-01 06:30:22 +01:00
full_name.len() == 12;
2020-03-03 14:39:25 +01:00
full_name == "Bob C. Davis";
2020-03-01 06:30:22 +01:00
full_name.pad(15, '$');
full_name.len() == 15;
2020-03-01 06:30:22 +01:00
full_name == "Bob C. Davis$$$";
full_name.truncate(6);
full_name.len() == 6;
2020-03-01 06:30:22 +01:00
full_name == "Bob C.";
full_name.replace("Bob", "John");
full_name.len() == 7;
2020-03-01 06:30:22 +01:00
full_name = "John C.";
full_name.contains('C') == true;
full_name.contains("John") == true;
full_name.clear();
full_name.len() == 0;
2020-02-25 03:43:13 +01:00
```
## Print and Debug
2020-02-25 08:01:50 +01:00
2020-02-25 03:43:13 +01:00
```rust
print("hello"); // prints hello to stdout
print(1 + 2 + 3); // prints 6 to stdout
print("hello" + 42); // prints hello42 to stdout
debug("world!"); // prints "world!" to stdout using debug formatting
```
2020-02-25 08:01:50 +01:00
### Overriding Print and Debug with Callback functions
2020-02-25 03:43:13 +01:00
```rust
// Any function that takes a &str argument can be used to override print and debug
2020-03-04 15:00:01 +01:00
engine.on_print(|x| println!("hello: {}", x));
engine.on_debug(|x| println!("DEBUG: {}", x));
// Redirect logging output to somewhere else
let mut log: Vec<String> = Vec::new();
engine.on_print(|x| log.push(format!("log: {}", x)));
engine.on_debug(|x| log.push(format!("DEBUG: {}", x)));
:
eval script
:
println!("{:?}", log); // 'log' captures all the 'print' and 'debug' results.
2016-04-14 03:52:12 +02:00
```
2016-03-31 15:59:54 +02:00
## Comments
```rust
let /* intruder comment */ name = "Bob";
// This is a very important comment
/* This comment spans
multiple lines, so it
only makes sense that
it is even more important */
/* Fear not, Rhai satisfies all your nesting
needs with nested comments:
/*/*/*/*/**/*/*/*/*/
*/
```
2017-11-04 11:18:56 +01:00
## Unary operators
```rust
let number = -5;
number = -5 - +5;
let booly = !true;
```
## Compound assignment operators
2017-11-04 11:18:56 +01:00
```rust
let number = 5;
number += 4;
number -= 3;
number *= 2;
number /= 1;
number %= 3;
number <<= 2;
number >>= 1;
```
The `+=` operator can also be used to build strings:
```rust
let my_str = "abc";
my_str += "ABC";
2020-02-25 03:43:13 +01:00
my_str += 12345;
2017-11-04 11:18:56 +01:00
2020-02-25 03:43:13 +01:00
my_str == "abcABC12345"
2017-11-04 11:18:56 +01:00
```