Add object maps.

This commit is contained in:
Stephen Chung
2020-03-29 23:53:35 +08:00
parent ef6c6ea6d2
commit 45ee51874f
9 changed files with 632 additions and 202 deletions

View File

@@ -272,6 +272,7 @@ The following primitive types are supported natively:
| **Unicode character** | `char` | `"char"` |
| **Unicode string** | `String` (_not_ `&str`) | `"string"` |
| **Array** (disabled with [`no_index`]) | `rhai::Array` | `"array"` |
| **Object map** (disabled with [`no_object`]) | `rhai::Map` | `"map"` |
| **Dynamic value** (i.e. can be anything) | `rhai::Dynamic` | _the actual type_ |
| **System number** (current configuration) | `rhai::INT` (`i32` or `i64`),<br/>`rhai::FLOAT` (`f32` or `f64`) | _same as type_ |
| **Nothing/void/nil/null** (or whatever you want to call it) | `()` | `"()"` |
@@ -999,7 +1000,7 @@ let foo = [1, 2, 3][0];
foo == 1;
fn abc() {
[42, 43, 44] // a function returning an array literal
[42, 43, 44] // a function returning an array
}
let foo = abc()[0];
@@ -1040,6 +1041,68 @@ print(y.len()); // prints 0
engine.register_fn("push", |list: &mut Array, item: MyType| list.push(Box::new(item)) );
```
Object maps
-----------
Object maps are dictionaries. Properties of any type (`Dynamic`) can be freely added and retrieved.
Object map literals are built within braces '`${`' ... '`}`' (_name_ `:` _value_ syntax similar to Rust)
and separated by commas '`,`'.
The Rust type of a Rhai object map is `rhai::Map`.
[`type_of()`] an object map returns `"map"`.
Object maps are disabled via the [`no_object`] feature.
The following functions (defined in the standard library but excluded if [`no_stdlib`]) operate on object maps:
| Function | Description |
| -------- | ------------------------------------------------------------ |
| `has` | does the object map contain a property of a particular name? |
| `len` | returns the number of properties |
| `clear` | empties the object map |
Examples:
```rust
let y = ${ // object map literal with 3 properties
a: 1,
bar: "hello",
baz: 123.456
};
y.a = 42;
print(y.a); // prints 42
print(y["bar"]); // prints "hello" - access via string index
ts.obj = y; // object maps can be assigned completely (by value copy)
let foo = ts.list.a;
foo == 42;
let foo = ${ a:1, b:2, c:3 }["a"];
foo == 1;
fn abc() {
${ a:1, b:2, c:3 } // a function returning an object map
}
let foo = abc().b;
foo == 2;
let foo = y["a"];
foo == 42;
y.has("a") == true;
y.has("xyz") == false;
print(y.len()); // prints 3
y.clear(); // empty the object map
print(y.len()); // prints 0
```
Comparison operators
--------------------