Skip to content

Commit

Permalink
Added constructors
Browse files Browse the repository at this point in the history
  • Loading branch information
Daniel Berezin committed Jun 8, 2019
1 parent d82e698 commit 518749f
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 14 deletions.
2 changes: 1 addition & 1 deletion docs/browser.e9f8be96.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

17 changes: 7 additions & 10 deletions examples/linkedList.lox
Original file line number Diff line number Diff line change
@@ -1,15 +1,12 @@
// Linked List via Classes
class Link {}

fun newLink (value, next) {
var link = Link();
link.value = value;
link.next = next;
link.append
return link;
class Link {
init(value, next) {
this.value = value;
this.next = next;
}
}

var ll = newLink(1, newLink(2, newLink(3, nil)));
var ll = Link(1, Link(2, Link(3, nil)));

fun traverse(n, fn) {
fn(n);
Expand All @@ -36,7 +33,7 @@ fun append(list, newNode) {
print "list:";
printList(ll);

append(ll, newLink(40, nil));
append(ll, Link(40, nil));

print "list:";
printList(ll);
12 changes: 9 additions & 3 deletions interpreter.js
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ class LoxCallable {
this.closure = closure
}

call(interpreter, args) {
call(interpreter, args, isInit = false) {
const env = new Environment(this.closure)
for (let param = 0; param < this.declaration.params.length; param++) {
env.set(this.declaration.params[param], args[param])
Expand All @@ -55,6 +55,9 @@ class LoxCallable {
throw ret
}
}

// Always return "this" if a function is an initializer
if (isInit) return this.closure.get({ name: { lexeme: 'this' } })
return null
}

Expand All @@ -76,8 +79,11 @@ class LoxClass extends LoxCallable {
this.methods = methods
}

call() {
return new LoxInstance(this)
call(interpreter, args) {
const instance = new LoxInstance(this)
const init = this.methods.get('init')
if (init) init.bind(instance).call(interpreter, args, true)
return instance
}

toString() {
Expand Down

0 comments on commit 518749f

Please sign in to comment.