Eliot’s Tips and Tricks

Local and Global Variables

This is small flaw in the language, but it is hard for the Lua designers to change, because it will break backward compatibility with existing code. If you define a variable in a function always remember to prefix it with the keyword “local” otherwise it will have global scope in the program. This code fragment illustrates the issue:

Here you can see that because the variable A was not explicitly defined as being local in scope, the fooBar() function can access the value it was set to in the foo() function.

Tagged: