Variables - cyxigo/wi GitHub Wiki
Introduction
Variables store values. You can create a variable with :=:
my_var := 10;
Wi is dynamically typed – no type annotations needed. Just name, :=, and a value. It's also, the only way to create a variable in Wi!
It's important to note that a value is any expression. We'll talk about them in the next page, when we talk about operators.
Declaration and Definition
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:
my_var := 10;
my_var is the declaration, and := 10 is the definition.
Modifying variables
It's simple. Just variable name, =, and new value:
my_var = 20;
Scopes
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:
{
a := 10;
}
std::puts(a);
a is called a local variable. This will cause a compile error because puts(a) is not in the same scope as a itself – it simply does not exist there.
Global scope
Any variable defined at the top-level code (outside any block) is a global variable and can be accessed by any scope:
x := 10;
{
std::puts(x); %% 10
}
Outer scopes
{
a := 1;
{
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.
Shadowing
Wi does not allow creating multiple variables with the same name in the same scope:
a := 10;
a := 20;
compile error: variable a is already defined
|
2 | a := 20;
| ^
--> file.wi:2:1
But Wi allows shadowing – inner scopes can declare a variable with the same name as one in the outer scope:
a := 10;
{
a := 20;
std::puts(a); %% 20
}
std::puts(a); %% 10, unchanged
Next: Operators