Crafting Interpreters · Week 12

Crafting Interpreters 22: Local Variables: reading guide

Read the chapterVerified by tests

Local variables on the VM stack: the compiler tracks locals and scope depth, so each local is just a stack slot index, making access much faster than hash lookups.

Time About 6 hours this week

Why it matters

This is how real compilers do register and stack slot allocation in simple form. It also explains why locals are faster than globals in Python and Lua.

How to approach it

Use the disassembler to watch GET_LOCAL and SET_LOCAL slot numbers. Trace a nested block example on paper.

Challenges

4 challenges at the end of the chapter.

Challenge 3 (const or final variables) and challenge 4 (more than 256 locals) are the implementable ones. Challenge 1 asks about faster local resolution.

Traps

  • Popping the wrong number of locals at the end of a scope.
  • Reading a local in its own initializer must be an error.

Verified by the book's chap22_local tests when you push your repo.

Links

Back to week 12