KonsolScript:Tutorials:Variables

From GPWiki
Jump to: navigation, search

Variables

Variables help your computer to remember values. Upon closing your program, all values assigned to variables will be forgotten.

Data types

KonsolScript can remember three types of data -- numeric, state, and textual values.

  • Number - remembers any numeric value.
  • Boolean - remembers any state (or better known to others as flags).
  • String - remembers any type of data as textual data.

User-Defined Variables

You can use variable to your program -- You just have to declare one using the syntax below. /*

* Var:DataType variable_name;
*/

By following the syntax, we can declare our variable named age. //declares age as Number variable

 Var:Number age;
 age = 24;

Variable Scope

  • Local Variables - these variables are only accessible inside the function it was declared.

function main() {

 foo()
 Konsol:Log("inside main() > " + x)

} function foo() {

 Var:Number x;
 x = 10;
 Konsol:Log("inside foo() > " + x)

} //Outputs... //inside foo() > 10 //Error in line 3 The sample above makes an error because x was declared inside foo function.

function main() {

 Var:Number x;
 x = 20;
 foo()
 Konsol:Log("inside main() > " + x)

} function foo() {

 Var:Number x;
 x = 10;
 Konsol:Log("inside foo() > " + x)

} //Outputs... //inside foo() > 10 //inside main() > 20 The sample above demonstrates a local variable on two different functions that uses same name would not cause error because neither was declared as global variable.

Var:Number x; function main() {

 x = 20;
 foo()
 Konsol:Log("inside main() > " + x)

} function foo() {

 Var:Number x;
 x = 10;
 Konsol:Log("inside foo() > " + x)

} //Outputs... //Error on line 8 The code above shows a conflicting declared Global and Local variable that uses same name. Once a variable was declared globally, it cannot be re-declared inside any function.

  • Global Variables - these variables are accessible from any functions that tries to store values to it.

Var:Number x; function main() {

 x = 20;
 foo()
 Konsol:Log("inside main() > " + x)

} function foo() {

 x = 10;
 Konsol:Log("inside foo() > " + x)

} //Outputs... //inside foo() > 10 //inside main() > 10 Although main function assigned 20 to x first, foo function will print out 10 since it stored the value 10 after main function did. And so, main function will also print 10.

Built-in Variables

KonsolScript declares some variables to act as the fake Direct Memory Access (also known as registers). For example, you can check if the Left-Mouse Button is pressed by checking the state of LMB (a built-in Boolean variable).

You can see the name of other built-in variables in FreeKE.log (when using FreeKE) or kwkse.log (when using Quixie).

All KonsolScript built-in variables are global variables.

~creek23~