reorganize module
This commit is contained in:
52
_archive/rhai_engine/rhaibook/language/shadow.md
Normal file
52
_archive/rhai_engine/rhaibook/language/shadow.md
Normal file
@@ -0,0 +1,52 @@
|
||||
Variable Shadowing
|
||||
==================
|
||||
|
||||
{{#include ../links.md}}
|
||||
|
||||
In Rhai, new [variables] automatically _shadow_ existing ones of the same name. There is no error.
|
||||
|
||||
This behavior is consistent with Rust.
|
||||
|
||||
```rust
|
||||
let x = 42;
|
||||
let y = 123;
|
||||
|
||||
print(x); // prints 42
|
||||
|
||||
let x = 88; // <- 'x' is shadowed here
|
||||
|
||||
// At this point, it is no longer possible to access the
|
||||
// original 'x' on the first line...
|
||||
|
||||
print(x); // prints 88
|
||||
|
||||
let x = 0; // <- 'x' is shadowed again
|
||||
|
||||
// At this point, it is no longer possible to access both
|
||||
// previously-defined 'x'...
|
||||
|
||||
print(x); // prints 0
|
||||
|
||||
{
|
||||
let x = 999; // <- 'x' is shadowed in a block
|
||||
|
||||
print(x); // prints 999
|
||||
}
|
||||
|
||||
print(x); // prints 0 - shadowing within the block goes away
|
||||
|
||||
print(y); // prints 123 - 'y' is not shadowed
|
||||
```
|
||||
|
||||
|
||||
~~~admonish tip "Tip: Disable shadowing"
|
||||
|
||||
Set [`Engine::set_allow_shadowing`][options] to `false` to turn [variables] shadowing off.
|
||||
|
||||
```rust
|
||||
let x = 42;
|
||||
|
||||
let x = 123; // <- syntax error: variable 'x' already defined
|
||||
// when variables shadowing is disallowed
|
||||
```
|
||||
~~~
|
Reference in New Issue
Block a user