LUA / CHAPTER 02

Lexical scope and accidental globals

Beginner

Keep bindings local and distinguish shadowing from assignment.

By the end of this chapter

  • Trace block-local names
  • Recognize writes to a global environment
  • Initialize a local from an outer binding

The idea

Lua local variables belong to a lexical block such as a function, loop body, or explicit do block. A local declaration creates a new binding even when an outer binding has the same name. Assignment without a matching local can instead reach the chunk’s environment, creating accidental shared state that unrelated code can observe.

The scope of a new local begins after its declaration, so an initializer can read an outer variable of the same name. Keep temporary names local and make intentional shared state part of an explicit table or module interface. When debugging, identify which binding each use refers to rather than assuming every occurrence of the same spelling represents the same storage location.

Lua example
local n=4
do
  local n=n+3
  print(n)
end
print(n)
Result
7
4

The initializer reads the outer four, then the inner binding shadows it until the do block ends.

Try it yourself

Refactor a helper so every temporary is local and its only result is a returned value.

Use your own editor for this exercise. Runnable challenges on CodeQuest are available for JavaScript, Python, and SQL.

CHECK YOUR UNDERSTANDING

Chapter checkpoint

An inner block declares local count while an outer count already exists. What does the declaration create?