# Ch 22: Local Variables

> Study guide to Crafting Interpreters chapter 22. Local variables on the VM stack: the compiler tracks locals and scope depth, so each local is just a stack…

Updated October 20, 2026.

## Summary {#summary}

Crafting Interpreters chapter 22, Local Variables: 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. Budget about 6 hours; the book's `chap22_local` tests check your code.

## Key facts {#key-facts}

- Week 20 of 145 on the cracked.guide path, in [Crafting Interpreters](https://cracked.guide/crafting-interpreters).
- Time budget: about 6 hours.
- Part of the book: clox (bytecode VM, C).
- Verified on cracked.guide when the official `chap22_local` tests pass on GitHub Actions.
- 4 challenges at the end of the chapter.

## Week 20 goals {#objectives}

By the end of week 20 you can:

- Implement locals as stack slots tracked by the compiler.
- Trace endScope as it pops the locals of a finished block.
- Explain why locals are much faster to reach than globals.

## This week's steps {#steps}

- Read the chapter: Use the disassembler to watch GET_LOCAL and SET_LOCAL slot numbers.
- Write the code in your lox repo: Type it into clox/ (C) yourself as you read, and get it running.
- Do the challenges (1–4): Challenge 3 (const or final variables) and challenge 4 (more than 256 locals) are the implementable ones.
- Push and let the tests verify it: Your repo runs the book's chap22_local tests on every push; passing marks this done.

## Why it matters {#why}

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 {#approach}

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

## Challenges {#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.

## Common traps {#traps}

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

## Links {#links}

- [Read the chapter: Ch 22: Local Variables](https://craftinginterpreters.com/local-variables.html)
- [Official repo: book source, both interpreters, test suite](https://github.com/munificent/craftinginterpreters)
- [Running the official test suite against your own interpreter (repo README)](https://github.com/munificent/craftinginterpreters#testing-your-implementation)

---

Source: https://cracked.guide/guide/ci-22
cracked.guide: A free, dated 145-week path to getting genuinely cracked at programming.
