"There are two ways to accidentally use a global when a local was intended. One is to misspell the name of a local variable. The other is to forget the local keyword. Both of these are common sources of bugs."
"If you are ever in doubt about the scope of a variable, start from the statement where the variable's name is used and search upwards for the following:
- A local statement that creates a variable of this name or a local function statement that creates a function of this name.
- A function definition (a function statement, local function statement, or function expression) that uses this name as a formal argument
- A for loop that uses this name as a loop variable
The first one of these that you run into whose scope extends to the statement where you started searching is the place where your (local) variable was created. If your search hits the top of the file without finding anything, the variable is global."
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment