Crafting Interpreters · Week 20

Ch 22: Local Variables

Updated

About 6 hoursVerified by tests

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.

Flashcards 6 cards for Anki and AnkiMobile · all decks

Anki deck.tsv

This week's steps

4 steps
  1. Read the chapter

    Use the disassembler to watch GET_LOCAL and SET_LOCAL slot numbers.

  2. Write the code in your lox repo

    Type it into clox/ (C) yourself as you read, and get it running.

  3. Do the challenges (1–4)

    Challenge 3 (const or final variables) and challenge 4 (more than 256 locals) are the implementable ones.

  4. Push and let the tests verify it

    Your repo runs the book's chap22_local tests on every push; passing marks this done.

Sign in to track this: tick each step off and it counts toward your week.

Your notes

Only you

Sign in to keep private notes on this guide, in Markdown. They stay yours: never on your profile, and you can export them all.

Discussion

0 posts

Questions about this chapter, tips, and what tripped you up. Hints over answers: full solutions go in a spoiler.

No posts yet. Ask a question or share a tip.

Sign in to postAnyone can read. Posting needs an account with a confirmed email.

Reference

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.

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

Spot a mistake? Report it

Back to week 20