mirror of https://github.com/japl-lang/japl.git
Added closures support and related example
This commit is contained in:
parent
4669b46b0b
commit
3e81325319
|
@ -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):
|
||||
|
|
|
@ -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
|
||||
|
|
|
@ -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".
|
|
@ -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
|
||||
|
||||
|
|
Loading…
Reference in New Issue