BASIC variables were default-global :P
m (→Complex Scope) |
(BASIC variables were default-global :P) |
||
| Line 10: | Line 10: | ||
No, it's not just a mouthwash. A variable's ''scope'' defines how visible it is to the rest of the program. The feature exists in most high-level languages, and [[Lua]] is no exception. | No, it's not just a mouthwash. A variable's ''scope'' defines how visible it is to the rest of the program. The feature exists in most high-level languages, and [[Lua]] is no exception. | ||
Variables can exist in two forms: "global," or "local." A global variable is accessible to everything and is not limited. This is the default functionality in Lua. This is unlike many other languages, such as PHP | Variables can exist in two forms: "global," or "local." A global variable is accessible to everything and is not limited. This is the default functionality in Lua. This is unlike many other languages, such as PHP and C, where a variable is always local unless declared global. This difference is important to note. A global variable is not limited to its file, function, or code block: | ||
foo = 1; | foo = 1; | ||
| Line 52: | Line 52: | ||
Whenever writing addons, it is important to understand the concept of a variable's scope, because it tells the author where a variable is defined (and in some cases, which variable will be used). In general, it is best, in most programming languages, to keep a limited-scope approach, that is, to minimize variable visibility. If a variable does not need to be accessed by other addons and files, it should be kept local. Excessive, unnecessary use of global variables is called "polluting the global namespace" and is often looked upon as a messy or sloppy programming practice. | Whenever writing addons, it is important to understand the concept of a variable's scope, because it tells the author where a variable is defined (and in some cases, which variable will be used). In general, it is best, in most programming languages, to keep a limited-scope approach, that is, to minimize variable visibility. If a variable does not need to be accessed by other addons and files, it should be kept local. Excessive, unnecessary use of global variables is called "polluting the global namespace" and is often looked upon as a messy or sloppy programming practice. | ||
=== Out Of Scope and Garbage Collection === | |||
A variable is said to have gone "out of scope" when it is no longer accessible by the currently executing code block. If a variable is out of scope, it is eligible for garbage collection. If no accessible references exist to the variable anymore, the variable will be garbage collected at some point in the future. Take note that this implies that global variables will never be garbage collected unless they are overwritten because they never go out of scope. | |||
== Local Variables == | == Local Variables == | ||