Return to homepage

DOSATO

Copyright © 2024 Sebastiaan Heins

1.7 Scopes

do scopes

A scope is a block of code that can be used to limit the visibility of variables.
Scopes are created when a function or block is called.

Example of a scope:

make int a = 1    
do {
    make int b = 2
    do say (a + b) // 3
}
do say (a + b) // Error: b is not defined

You can see how the variable b is not defined outside of the scope of the block.
This is because the variable b is only visible inside the block.
Similarly, the variable a is visible inside and outside of the block, because it is defined outside of the block.

Function scopes

Functions have their own scope.
Variables defined inside of a function are only visible inside of the function.
Example of a function scope:

define sayAAA() {
    make int a = 1
    do say (a) // 1
}
do say (a) // Error: a is not defined

However, just like blocks, variables defined outside of a function are visible inside of the function.
Example of a function scope with a variable defined outside of the function:

make int a = 1
define sayAAA() {
    do say (a) // 1
}
do say (a) // 1

You can see how the variable a is visible inside and outside of the function.
This is because the variable a is defined outside of the function.

Global precedence

Only 1 variable can be defined with the same name in the same scope.
If a variable is defined with the same name as a variable outside of the scope, the variable at the lowest scope will be used.

Example:

make int a = 1
define sayAAA() {
    make int a = 2
    do say (a) // 2
}
do say (a) // 1

You can see how the variable a is defined twice.
The variable a is defined outside of the function and inside of the function.
The variable a inside of the function is used instead of the variable a outside of the function.

Garbage collection

Variables are automatically deleted when they are no longer in use.
Even complex types like arrays are automatically deleted when they are no longer in use.
Dosato is a memory safe language, so you don't have to worry about memory leaks.