Merge pull request #195 from jjspace/patch-1

Custom function scope Doc adjustments
This commit is contained in:
danielyxie 2018-02-28 12:14:07 -06:00 committed by GitHub
commit 2701db160b
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -908,13 +908,49 @@ The example above prints the following in its log::
15
11
For those with experience in other languages, especially Javascript it may be important to note that function declarations are not hoisted and must be declared BEFORE you use them.
print(hello());
function hello() {
return "world";
}
Will cause an error saying `variable hello not defined` whereas::
function hello() {
return "world";
}
print(hello());
Will print out
world
**Note about variable scope in functions:**
Functions can access "global" variables declared outside of the function's scope. However, they cannot change the value of any "global" variables.
Any changes to "global" variables will only be applied locally to the function. This also means that any variable that is first defined inside a
function will NOT be accessible outside of the function.
Any changes to "global" variables will only be applied locally to the function.
For example, the following code::
The following example shows that any change to "global" variable inside a function only applies in the function's local scope::
function foo() {
i = 5;
return "foo";
}
i = 0;
print(i);
foo();
print(i);
Results in the following log::
0
0
Furthermore, this also means that any variable that is first defined inside a function will NOT be accessible outside of the function as shown in the following example::
function sum(values) {
res = 0;
@ -933,22 +969,7 @@ results in the following runtime error::
Args:[]
variable res not defined
The following example shows that any change to "global" variable inside a function only applies in the function's local scope::
function foo() {
i = 5;
return "foo";
}
i = 0;
print(i);
foo();
print(i);
Results in the following log::
0
0
**Other Notes about creating your own functions:**