View Single Post
08-23-13, 08:47 PM   #6
Rainrider
A Firelord
AddOn Author - Click to view addons
Join Date: Nov 2008
Posts: 454
Originally Posted by Phanx View Post
6. Keep variables limited to the narrowest scope necessary. For example, if a variable is only used inside a loop, define it locally inside the loop, not outside.
I have the following code:
lua Code:
  1. local AddComboPointsBar = function(self, width, height, spacing)
  2.     local comboPoints = {}
  3.     local maxCPoints = MAX_COMBO_POINTS
  4.  
  5.     for i = 1, maxCPoints do
  6.         local cPoint = self.Overlay:CreateTexture("oUF_Rain_ComboPoint_"..i, "OVERLAY")
  7.         cPoint:SetSize((width - maxCPoints * spacing - spacing) / maxCPoints, height)
  8.         cPoint:SetPoint("BOTTOMLEFT", self.Overlay, (i - 1) * cPoint:GetWidth() + i * spacing, 1)
  9.         cPoint:SetTexture(unpack(ns.colors.cpoints[i]))
  10.         comboPoints[i] = cPoint
  11.     end
  12.  
  13.     self.CPoints = comboPoints
  14. end

If we would ignore the fact that I need maxCPoints as an upper bound for the loop for the sake of the example, wouldn't it be still better to define maxCPoints outside the for-loop, despite it is only needed inside? Wouldn't this spare me a global look-up for MAX_COMBO_POINTS and a garbage collection on every loop iteration? I don't know how GC works in loops, but if it collects on every iteration would this be cheaper than having to move one scope up to find maxCPoints?

The other question is whether it is better to use:
Code:
cPoint:SetTexture(ns.colors.cpoints[i][1], ns.colors.cpoints[i][2], ns.colors.cpoints[i][3])
instead of the function call to unpack? I mean is there something like "a function call equals this many table look-ups"?
  Reply With Quote