→Lazy Coding
(Typo fixing using AWB) |
|||
| Line 11: | Line 11: | ||
One stumbling block for Lua programmers coming from other languages is the fact that all variables are global unless specified otherwise. Many times, the use of global variables is necessary: saved variables are created via the global environment; all API functions and UI frames are in the global namespace. However, globals come at a cost of both performance, and naming conflicts. | One stumbling block for Lua programmers coming from other languages is the fact that all variables are global unless specified otherwise. Many times, the use of global variables is necessary: saved variables are created via the global environment; all API functions and UI frames are in the global namespace. However, globals come at a cost of both performance, and naming conflicts. | ||
Globals | Globals are inefficient to access compared to locals. Whenever a global is accessed, Lua has to call the internal equivalent of getfenv() to figure out where to retrieve the global from. Local variables, on the other hand, are stored on a stack. In code where performance is important (for instance an [[UIHANDLER OnUpdate|OnUpdate handler]]), it's often beneficial to create a local alias to a global function: | ||
local Foo = Foo | local Foo = Foo | ||
| Line 107: | Line 107: | ||
DoStuff() | DoStuff() | ||
end | end | ||
if foo | if foo and foo[bar] == 5 then -- will not throw an error | ||
DoStuff() | DoStuff() | ||
end | end | ||