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. plan_trip()runs the function, so you can see the local prints first.- After the call,
destinationdoes not exist globally. InLua, reading an undeclared variable yieldsnil. Theifcheck prints a clear message instead of trying to concatenatenilto a string (which would cause an error). - The final print shows the global
travel_modeis still "Plane." The local shadow did not modify it.
Note: If you want to change a global variable inside a function, just assign to it without using local. For example, travel_mode = "Car" inside a function would update the global variable. Using local travel_mode = "Car" would instead create a new local variable that only exists inside the function.
Guidelines to remember:
- Prefer
localvariables by default. They are safer and limit unintended side effects. - Only use globals when you have a strong reason and clear naming.
- Be careful with shadowing; it is legal but can be confusing if overused.
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.
