Lesson 11 of 55
9 mins readPython Variable Scoping: local vs global & do ... end Blocks
In Plain English
In Lua, variables without `local` are globally scoped by default! Always declare variables with `local` for performance, lexical privacy, and clean garbage collection.
Deep Dive: How It Works
Always Use local: Global lookups incur table hash search overhead; local variables reside directly in CPU VM registers.
do ... end Blocks: Explicitly limit variable lifetimes and create isolated scopes.
Lexical Closures: Inner scopes can read and mutate enclosing local variables.
Core Rules to Remember

Local is Faster & Safer: Local variables use fast register indexes instead of global table lookups.

do ... end Blocks: Creates a private lexical block that discards local variables at `end`.
Live Interactive Example
Hit Run Code to see it liveLexical Scoping in do ... end Blocks
Python 3.12
1
2
3
4
5
6
7
8
9
Output Console
Click "Run Code" to view the rendered output.
How it works: inner was destroyed upon exiting the do ... end block.
Your Turn: Micro Challenge
No pressure! Edit the starter code below and test your solution with instant feedback.
Micro Exercise
Isolate Variable in do Block
Declare `local counter = 10`.
Inside a `do ... end` block, declare `local factor = 3` and print `"Product: " .. (counter * factor)`.
1
2
Sandbox Output
Click "Run & Check" to test your solution.
Finished reading and practicing?
Mark this lesson as completed to update your course progress.