View Single Post
11-06-10, 04:48 AM   #6
Xinhuan
A Chromatic Dragonspawn
 
Xinhuan's Avatar
AddOn Author - Click to view addons
Join Date: Feb 2007
Posts: 174
Basically, use locals where possible, they are on the stack and gets cleaned when the function returns. The main reason to use upvalues is to share or store data in a scope larger than a function itself.


Use upvalues in these cases:
A) Data needs to be shared across multiple functions. In this case, your upvalue could be as simple as just being a boolean, or it can be as complex as a complete table (such as your SavedVariables).

B) Data or intermediate results doesn't need to be shared, but is expensive to calculate on demand. Thus you want to cache them as upvalues to reuse them inexpensively.

Here's a somewhat contrived example:

Code:
for i = 1, 40 do
    local unitID = format("raid%d", i)
    -- Do stuff with unitID
end
Now clearly recreating the strings "raid1" through "raid40" via the format() function or string..integer concatenation is somewhat expensive compared to this

Code:
-- At the top of the file
local RaidIDs = {}
for i = 1, 40 do
    RaidIDs[i] = format("raid%d", i)
end

-- Later in some function or OnUpdate or very frequent event handler
for i = 1, 40 do
    local unitID = RaidIDs[i]
    -- Do stuff with unitID
end
We cached the 40 unitID strings in a table and simply used it later. This is just another example of the memory vs speed problem in programming.
__________________
Author of Postal, Omen3, GemHelper, BankItems, WoWEquip, GatherMate, GatherMate2, Routes and Cartographer_Routes

Last edited by Xinhuan : 11-06-10 at 04:50 AM.
  Reply With Quote