Variable Scope: What You Will Learn

In the last lesson, you returned values from functions so the caller could decide what to do with the result. As a quick reminder, that approach made your code more flexible and reusable. Today, you will learn another key building block: variable scope. Scope controls where a variable can be seen and used. You will see how local and global variables work in Lua, how shadowing happens, and why avoiding globals keeps your programs safer.

Scope in Action: Local vs Global (and Shadowing)

Explanation:

  • travel_mode is declared without local, so it becomes global. It can be accessed anywhere. While Lua allows this, you should avoid globals because they are hard to track and can be changed by any part of the program.
  • Inside plan_trip, destination is declared with local. It exists only inside the function. Printing it works there, but it disappears after the function finishes.
  • The local travel_mode inside plan_trip shadows the global travel_mode. Inside the function, the local value ("Ship") is used; outside, the global value ("Plane") remains unchanged.
Summary and Next Steps

You learned how scope controls visibility:

  • Local variables live only where they are declared (like inside a function).
  • Global variables are visible everywhere and should be used sparingly.
  • Shadowing lets a local variable temporarily hide a global with the same name.
  • Accessing an undeclared variable yields nil in Lua, so handle it safely.

Great work building on your function skills with clean scoping habits. Head to the practice section to apply these ideas and gain confidence using locals, globals, and shadowing in real code.

Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal