WoW:UI best practices: Difference between revisions

(Added some links)
 
Line 9: Line 9:
== Use local variables ==
== Use local variables ==


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 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 in Lua are actually fields in a table called _G. In order to access a global variable, Lua internally translates the variable name to _G["variable name"]. Local variables, on the other hand, are stored on a stack. Stack access is always faster than indexing a table. 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:
Globals in Lua are actually fields in a table called _G. In order to access a global variable, Lua internally translates the variable name to _G["variable name"]. Local variables, on the other hand, are stored on a stack. Stack access is always faster than indexing a table. 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:
Anonymous user