Added closures support and related example

This commit is contained in:
nocturn9x 2020-07-29 16:52:47 +02:00
parent 4669b46b0b
commit 3e81325319
4 changed files with 19 additions and 3 deletions

View File

@ -246,7 +246,7 @@ class Interpreter(object):
def visit_function(self, statement):
"""Visits a function"""
function = JAPLFunction(statement)
function = JAPLFunction(statement, self.environment)
self.environment.define(statement.name.lexeme, function)
def exec(self, statement: Statement):

View File

@ -37,14 +37,15 @@ class Type(Callable):
class JAPLFunction(Callable):
"""A generic wrapper for user-defined functions"""
def __init__(self, declaration):
def __init__(self, declaration, closure):
"""Object constructor"""
self.declaration = declaration
self.arity = len(self.declaration.params)
self.closure = closure
def call(self, interpreter, arguments):
scope = Environment(interpreter.globals)
scope = Environment(self.closure)
for name, value in zip(self.declaration.params, arguments):
scope.define(name.lexeme, value)
interpreter.in_function = True

13
closure.jpl Normal file
View File

@ -0,0 +1,13 @@
fun makeCounter() {
var i = 0;
fun count() {
i = i + 1;
print i;
}
return count;
}
var counter = makeCounter();
counter(); // "1".
counter(); // "2".

View File

@ -5,6 +5,8 @@
2 + 2;
-1 * 6;
3 * (9 / 2); // Parentheses for grouping
8 % 2; // Modulo division
6 ** 9; // Exponentiation
// Variable definition and assignment