WoW:UI best practices: Difference between revisions

(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 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 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[bar] and foo[bar] == 5 then -- will not throw an error
  if foo and foo[bar] == 5 then -- will not throw an error
     DoStuff()
     DoStuff()
  end
  end
Anonymous user