Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save yitonghe00/713a3b916ffd59ebbc6878367d5c8195 to your computer and use it in GitHub Desktop.
Save yitonghe00/713a3b916ffd59ebbc6878367d5c8195 to your computer and use it in GitHub Desktop.
specialForms.set = (args, scope) => {
if (args.length !== 2 || args[0].type !== "word") {
throw new Error("Incorrect use of set.");
}
const value = evaluate(args[1], scope);
for(let outerScope = scope; scope; outerScope = Object.getPrototypeOf(outerScope)) {
if (Object.prototype.hasOwnProperty.call(outerScope, args[0].name)) {
// Found the binding at the level
outerScope[args[0].name] = value;
return value;
}
// Binding not found until the topScope
throw new ReferenceError("Binding not exist.");
};
run(`
do(define(x, 4),
define(setx, fun(val, set(x, val))),
setx(50),
print(x))
`);
// → 50
run(`set(quux, true)`);
// → Some kind of ReferenceError
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment