-
Notifications
You must be signed in to change notification settings - Fork 0
Variables
Variables store values. You can create a variable with var:
var my_var = 10;Wi is dynamically typed - no type annotations needed. Just var, name, =, and value.
Before looking further into scopes, first I want to make some terminology clear:
- Declaring a variable means introducing it to Wi
- Defining a variable means providing an actual value for it
So in:
var my_var = 10;var my_var is the declaration, and = 10 is the definition.
It's simple. Just variable name, =, and new value:
my_var = 20;A scope is a region of code where a variable is visible and can be accessed. Wi has block scope - variables only exist inside the block {} where they were created.
For example:
{
var a = 10;
}
print(a);a is called a local variable. This will cause a runtime error because print(a) is not in the same scope as a itself - it simply does not exist there.
Any variable defined at the top-level code (outside any block) is a global variable and can be accessed by any scope:
var x = 10;
{
print(x); // 10
}{
var a = 1;
{
var b = 2;
}
}Here, for scope where b lives ("b" scope), outer scope is where a lives ("a" scope).
"b" scope can access all variables defined in "a" scope, because "a" is its outer scope. This is the same reason all scopes can access globals - globals are always an outer scope.
"a" scope cannot access "b" scope variables. They do not exist for "a" scope. For "a" scope, "b" scope is the inner scope.
Wi does not allow creating multiple variables with the same name in the same scope:
var a = 10;
var a = 20;runtime error: variable a is already defined
--> file.wi:2 in main function
But Wi allows shadowing - inner scopes can declare a variable with the same name as one in the outer scope:
var a = 10;
{
var a = 20;
print(a); // 20
}
print(a); // 10, unchangedNext: Operators