This tutorial directly continues from the previous one on blocks. This is because blocks and variable scope are often taught together.

What is Variable Scope

Variable scope in short is the lifetime of a variable. Variables declared in a particular area are not available throughout the entire code. They are available to only select blocks.

Different Types Of Variable Scope

There are two types of variable scope -
  • Class - These are variables that are declared in the class block. They are known throughout the class.
  • Block - These are variables declared in blocks within the class block ( could be a function block or a block within a function ). They are known only within that block and are destroyed when the execution of that block is complete.

Example Of Class and Block Scope

class Main
  var a:Int;
  function hello()
    var b = 2;
      var c = 10;
In this snippet of code,
  • a is a class scope variable
  • b is a function scope variable ( block scope )
  • c is within a block scope that is inside the function block

It should be noted that a can be accessed form anywhere in the class, while b can be accessed only within the function hello(), and the variable c can be accessed only from the block in which it was declared.