म
MarathiCodeby Sprout Tech
Documentation topicsScope
MarathiCode v0.2.0

Scope

व्याप्ती

Every variable belongs to a scope. Scopes are nested:

scopes.txt
Global scope (the whole program)
  └─ Function scope (one per call: parameters and local variables)
       └─ Block scope (each { } of जर, नाहीतर, पर्यंत, साठी)
  • A name is looked up in the current scope first, then in each enclosing scope, up to the global scope.
  • चल always creates the variable in the current scope.
  • Variables created inside a block or function disappear when it ends.
  • A function body's enclosing scope is the global scope, not the scope of the caller.

Block scope and shadowing

block_scope.mr
चल x = "बाहेर"
जर खरे तर {
    चल x = "मधला"
    जर खरे तर {
        चल x = "आतला"
        छापा(x)
    }
    छापा(x)
}
छापा(x)
Output (आउटपुट)
आतला
मधला
बाहेर

Variables do not leak out of blocks

no_leak.mr
जर खरे तर {
    चल गुप्त = 99
}
छापा(गुप्त)
Output / Error (आउटपुट / त्रुटी)
धावपळ त्रुटी (Runtime Error)
ओळ 4:
    छापा(गुप्त)
चल 'गुप्त' परिभाषित नाही.

Function scope

Parameters and चल variables inside a function are local to each call. A function can read and update global variables:

function_scope.mr
चल गणना = 0
चल n = 100

कार्य वाढवा(n) {
    चल स्थानिक = n * 2
    गणना = गणना + स्थानिक
}

वाढवा(1)
वाढवा(5)
छापा(गणना)
छापा(n)
Output (आउटपुट)
12
100

A function cannot see the local variables of the code that called it:

caller_scope.mr
कार्य पहा() {
    परत खाजगी
}
कार्य बोलवा() {
    चल खाजगी = 1
    परत पहा()
}
बोलवा()
Output / Error (आउटपुट / त्रुटी)
धावपळ त्रुटी (Runtime Error)
ओळ 2:
        परत खाजगी
चल 'खाजगी' परिभाषित नाही.

Loop variables follow the same rules; see Loops.