Closures · Crafting Interpreters
BRANK

25ClosuresThis book is a work in progress!×If you see a mistake, find something unclear, or have a suggestion, please let me know. To learn when new chapters are up, join the mailing list:(I post about once a month. Don’t worry, I won’t spam you.)As the man said, for every complex problem there’s a simple solution, and it’s wrong. Umberto Eco, Foucault’s PendulumThanks to our diligent labor in the last chapter, we have a virtual machine with working functions. What it lacks is closures. Aside from global variables, which are their own breed of animal, a function has no way to reference a variable declared outside of its own body:var x = "global"; fun outer() { var x = "outer"; fun inner() { print x; } inner(); } Run this example now and it prints “global”. It’s supposed to print “outer”. To fix this, we need to include the entire lexical scope of all surrounding functions when resolving a variable.This problem is harder in clox than it was in jlox because our byt…

craftinginterpreters.com
Related Topics: