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.
Explanation:
travel_modeis declared withoutlocal, so it becomes global. It can be accessed anywhere. WhileLuaallows this, you should avoid globals because they are hard to track and can be changed by any part of the program.- Inside
plan_trip,destinationis declared withlocal. It exists only inside the function. Printing it works there, but it disappears after the function finishes. - The local
travel_modeinsideplan_tripshadows the globaltravel_mode. Inside the function, the local value ("Ship") is used; outside, the global value ("Plane") remains unchanged.
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
nilinLua, 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.
