How Closures Capture Variables
There is a long time since I worked on compilers at this level, so my memory of this is a bit rusty. Conceptually you have a hierarchical symbol table. When the compiler finds a variable and tries to associate that with a place in e.g. memory it will look at the inner most symbol table first.
If the symbol is not found there it will move up the chain to the symbol table higher up until it finds the memory location of name in this case. The generated machine code will then use that address when reading and writing to the name variable.
That is one way of looking at it. If we are dealing with an interpreter, variables I supposed could all be in some large dictionary. What you are really looking up then is the unique key to this dictionary.
The Lua programming language makes this sort of thing quite explicit. Everything is based off hash tables having meta hash tables, which can have meta hash table indefinitely.
When you look up a key in the hash table and it is not there, you simply follow a pointer in that hash table to its meta hash table, and attempt to do a lookup there.
I suppose each scope could thus be represented by a hash table where the surrounding scope is a meta hash table of that scope’s hash table.