Skip to content

Commit 4fbf6dd

Browse files
committed
[update] the resolver to mark closure variables as used once discovered.
1 parent 5413d5c commit 4fbf6dd

File tree

4 files changed

+34
-2
lines changed

4 files changed

+34
-2
lines changed

README.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -20,8 +20,8 @@ This language is still currently experimental with many more features to come.
2020
* [Variables](examples/variable.ls).
2121
* [Conditionals](examples/conditionals.ls).
2222
* [Logical operators](examples/logical.ls).
23-
* Loops.
24-
* Closures.
23+
* [Loops](examples/loops.ls).
24+
* [Closures](examples/closure.ls).
2525
* [Recursion](examples/recursion.ls).
2626
* Blocks.
2727
* Printing.

examples/closure.ls

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
// closure wraps function and keeps one variable named counter for internal
2+
// state.
3+
func Closure() {
4+
var counter = 0;
5+
6+
func Increment() {
7+
counter = counter + 1;
8+
return counter;
9+
}
10+
11+
return Increment;
12+
}
13+
14+
// Gets a function from the closure back.
15+
var counter = Closure();
16+
17+
// Calling counter() increments the counter.
18+
print counter();
19+
print counter();

examples/loops.ls

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
var x = 0;
2+
3+
// your typical while loop.
4+
while (x < 10) {
5+
print x;
6+
x = x + 1;
7+
}
8+
9+
// Your typical for loop that does the same thing as the while.
10+
for (var y = 0; y < 10; y = y + 1) {
11+
print y;
12+
}

src/Lamscript/parsing/Resolver.cpp

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -330,6 +330,7 @@ void Resolver::ResolveLocalVariable(
330330
for (int pos = scope_stack_.size() - 1; pos >= 0; pos--) {
331331
if (scope_stack_[pos].contains(variable_name.Lexeme)) {
332332
interpreter_->Resolve(expression, scope_stack_.size() - 1 - pos);
333+
scope_stack_[pos][variable_name.Lexeme].Used = true;
333334
return;
334335
}
335336
}

0 commit comments

Comments
 (0)