Variables Scope¶
This section needs improvements.
Certain parts of this section are poorly worded, poorly illustrated and might be confusing. Those will be updated at some point.
Variable scope refers to the region of script from where a variable can be accessed. There are a few different scopes in XS:
- File scope.
- Global scope.
- Local scope.
1. File Scope¶
Variables defined in a file, outside of any function or rule, are file scoped. They can be accessed from any function or rule in the same file, provided that such function or rule is defined after the variable's definition. They cannot be accessed from any other file.
File scoped variables.
file-scope-test.xs | |
---|---|
Lifetime¶
File-scoped variables keep their values between function calls:
Lifetime of file-scoped variables.
2. Global Scope¶
Variables defined in a file, outside of any function or rule, and marked with
the extern
keyword, are global scoped. They can be accessed from
any function or rule in any file where the file containing the variable is
included, provided that such function or rule is defined after the variable's
definition.
These variables are commonly referred to as global variables.
Global scoped variables.
global-scope-test.xs | |
---|---|
Lifetime¶
Like file-scoped variables, global variables also keep their values between function calls.
3. Local Scope¶
Variables defined inside a function are local to that function. They can only be accessed from within that function.
These variables are commonly referred to as local variables.
There are two types of local variables:
- non-
static
variables static
variables
3.1. Non-static
variables¶
Non-static
local variable.
Lifetime¶
Non-static variables lose their values between function calls.
Lifetime of non-static
local variables.
3.2. static
variables¶
These variables are marked with the static
keyword. They keep their
values between function calls.