|
Spec-Zone .ru
спецификации, руководства, описания, API
|
Variables can be declared at the script level (script variable), inside a class (instance variable), or within blocks (local variable)
Script variables are variables which are declared at the top-level of a script (as opposed to inside a class definition or block). Script variables are visible through-out the entire script -- a member access expression is not needed.
var thing = "Thing";
class A {
function getThing() : String { thing }
}
Without an added access modifer, script variables are not visible outside the script. If access modifiers are added which make the script variable visible outside the script, they may be accessed as members of the script. Access modifiers for variables are: public, protected, package, public-read, and public-init -- see the Access Modifiers chapter. For example, if this is script Foo.fx:
public def bohr = 0.529177e-10
Then script Noof.fx can access bohr:
println(Foo.bohr)
The lifetime of a script variable is from the time the script is loaded until the end of program execution.
Instance variables are declared at the top-level of a class. Within the declaring class (and its subclasses) instance variables are accessed simply by use of the variable name. Otherside of the class, there are accessed through the object of which they are a member. For example:
def anA = A{ rat: true };
println(anA.rat);
class A {
var rat : Boolean;
function isIt() { rat }
}
class B {
function wellisIt() { anA.rat }
}
Access modifiers (public, protected, package, public-read, and public-init) control the visiblity of instance variables. If no access modifers are provided, instance variables are visible only within the script.
The lifetime of an instance variable is the lifetime of the class instance.
Local variables are declared within blocks, including blocks which are the bodies of functions. Local variables are visible only within the inner-most block -- their scope includes the entire body of that block (not just below the variable declaration). Member access expressions are not applicable to local variables. Access modifiers must not be applied to local variable declarations.
[To do: explain why the whole-block scoping rule, and give example]
The lifetime of a local variable ends when the block is exited.
Unlike script and instance variables, local variable declarations are expressions, that is, they have type and value. Their type is the type of the variable and their value is the value of the variable.
Function parameters are visible only within the function body. For-expression induction variables are visible only within the for-expression body. The scope of other expression parameters is their expression.
They must not be assigned to.
See the Functions chapter, the for-expression, and on replace for syntax.