Variable Scope

In Lua, variables can either be local or global, and understanding the difference is crucial for writing efficient and maintainable code.

  • Local Variables are confined to the scope in which they are declared (such as within a function). They are temporary and automatically cleared from memory when they go out of scope. Variables are global by default, to make a variable local it must be preceded with local.

  • Global Variables are accessible throughout the entire script and stay in memory as long as the component is running. This can lead to memory leaks because global variables persist even when no longer needed.

Always try to use local variables whenever possible:

  1. Avoid Interference Between Functions: Local variables are isolated within their scope, preventing them from unintentionally affecting other parts of the code. Also see Function scope.

  2. Prevent Memory Leaks: Since global variables stay in memory until the component stops, they can cause memory leaks if not managed properly.

To monitor the number of global variables in your script, you can check the global environment using the _G table, which holds all globally declared variables.