implementing closures (ch25)
This commit is contained in:
13
samples/ch25_closures1.lox
Normal file
13
samples/ch25_closures1.lox
Normal file
@ -0,0 +1,13 @@
|
||||
// this program should print "outer"; without proper closure support, it shows "global".
|
||||
|
||||
var x = "global";
|
||||
|
||||
fun outer() {
|
||||
var x = "outer";
|
||||
fun inner() {
|
||||
print x;
|
||||
}
|
||||
inner();
|
||||
}
|
||||
|
||||
outer();
|
22
samples/ch25_closures2.lox
Normal file
22
samples/ch25_closures2.lox
Normal file
@ -0,0 +1,22 @@
|
||||
fun makeClosure() {
|
||||
var local = "local";
|
||||
fun closure() {
|
||||
print local;
|
||||
}
|
||||
return closure;
|
||||
}
|
||||
|
||||
var closure = makeClosure();
|
||||
closure();
|
||||
|
||||
fun makeClosure2(value) {
|
||||
fun closure() {
|
||||
print value;
|
||||
}
|
||||
return closure;
|
||||
}
|
||||
|
||||
var doughnut = makeClosure("doughnut");
|
||||
var bagel = makeClosure("bagel");
|
||||
doughnut();
|
||||
bagel();
|
11
samples/ch25_closures3.lox
Normal file
11
samples/ch25_closures3.lox
Normal file
@ -0,0 +1,11 @@
|
||||
fun outer() {
|
||||
var a = 1;
|
||||
var b = 2;
|
||||
fun middle() {
|
||||
var c = 3;
|
||||
var d = 4;
|
||||
fun inner() {
|
||||
print a + c + b + d;
|
||||
}
|
||||
}
|
||||
}
|
8
samples/ch25_closures4.lox
Normal file
8
samples/ch25_closures4.lox
Normal file
@ -0,0 +1,8 @@
|
||||
fun outer() {
|
||||
var x = "outside";
|
||||
fun inner() {
|
||||
print x;
|
||||
}
|
||||
inner();
|
||||
}
|
||||
outer();
|
10
samples/ch25_closures5.lox
Normal file
10
samples/ch25_closures5.lox
Normal file
@ -0,0 +1,10 @@
|
||||
fun outer() {
|
||||
var x = "outside";
|
||||
fun inner() {
|
||||
print x;
|
||||
}
|
||||
return inner;
|
||||
}
|
||||
|
||||
var closure = outer();
|
||||
closure();
|
22
samples/ch25_closures6.lox
Normal file
22
samples/ch25_closures6.lox
Normal file
@ -0,0 +1,22 @@
|
||||
var globalSet;
|
||||
var globalGet;
|
||||
|
||||
fun main() {
|
||||
var a = "initial";
|
||||
|
||||
fun set() {
|
||||
a = "updated";
|
||||
}
|
||||
|
||||
fun get() {
|
||||
print a;
|
||||
}
|
||||
|
||||
globalSet = set;
|
||||
globalGet = get;
|
||||
}
|
||||
|
||||
main();
|
||||
|
||||
globalSet();
|
||||
globalGet();
|
Reference in New Issue
Block a user