Add local functions and closure
parent
3ac911b666
commit
714cf80229
@ -1,34 +1,28 @@
|
|||||||
package fr.celticinfo.lox
|
package fr.celticinfo.lox
|
||||||
|
|
||||||
class LoxFunction : LoxCallable {
|
class LoxFunction(
|
||||||
private val declaration: Function
|
private val declaration: Function,
|
||||||
|
private val closure: Environment
|
||||||
constructor(declaration: Function) {
|
) : LoxCallable {
|
||||||
this.declaration = declaration
|
|
||||||
}
|
|
||||||
|
|
||||||
override fun call(interpreter: Interpreter, arguments: List<Any?>): Any? {
|
override fun call(interpreter: Interpreter, arguments: List<Any?>): Any? {
|
||||||
val environment = Environment(interpreter.globals)
|
val environment = Environment(closure)
|
||||||
|
|
||||||
for (i in declaration.params.indices) {
|
for (i in declaration.params.indices) {
|
||||||
environment.define(declaration.params[i].lexeme, arguments[i])
|
environment.define(declaration.params[i].lexeme, arguments[i])
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
return try {
|
||||||
interpreter.executeBlock(declaration.body, environment)
|
interpreter.executeBlock(declaration.body, environment)
|
||||||
|
null
|
||||||
} catch (returnValue: LoxReturn) {
|
} catch (returnValue: LoxReturn) {
|
||||||
return returnValue.value
|
returnValue.value
|
||||||
}
|
}
|
||||||
|
|
||||||
return null
|
|
||||||
}
|
}
|
||||||
|
|
||||||
override fun arity(): Int {
|
override fun arity() = declaration.params.size
|
||||||
return declaration.params.size
|
|
||||||
}
|
override fun toString() = "<fn ${declaration.name.lexeme}>"
|
||||||
|
|
||||||
override fun toString(): String {
|
|
||||||
return "<fn ${declaration.name.lexeme}>"
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
}
|
||||||
Loading…
Reference in New Issue