Originally Posted by Phanx
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:
local AddComboPointsBar = function(self, width, height, spacing)
local comboPoints = {}
local maxCPoints = MAX_COMBO_POINTS
for i = 1, maxCPoints do
local cPoint = self.Overlay:CreateTexture("oUF_Rain_ComboPoint_"..i, "OVERLAY")
cPoint:SetSize((width - maxCPoints * spacing - spacing) / maxCPoints, height)
cPoint:SetPoint("BOTTOMLEFT", self.Overlay, (i - 1) * cPoint:GetWidth() + i * spacing, 1)
cPoint:SetTexture(unpack(ns.colors.cpoints[i]))
comboPoints[i] = cPoint
end
self.CPoints = comboPoints
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"?