Variable Shadowing

In Rhai, new variables automatically shadow existing ones of the same name. There is no error.

This behavior is consistent with 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

Tip: Disable shadowing

Set Engine::set_allow_shadowing to false to turn variables shadowing off.

let x = 42;

let x = 123;        // <- syntax error: variable 'x' already defined
                    //    when variables shadowing is disallowed