View Single Post
08-05-14, 09:17 AM   #1
zork
A Pyroguard Emberseer
 
zork's Avatar
AddOn Author - Click to view addons
Join Date: Jul 2008
Posts: 1,740
local function or object:Function, what to pick?

Is there any major benefit of using one over the other?

I asked this in another thread lately and Phanx posted the prototype trick which is kind of neat.

local function variant

Lua Code:
  1. local function ResetAllModels()
  2.     for i, model in pairs(self.models) do
  3.       ModelReset(model)
  4.     end
  5.   end    
  6.    
  7.   local function ModelReset(...)
  8.     print("ModelReset",...)
  9.   end
  10.  
  11.   local function ModelOnMouseDown(...)
  12.     print("ModelOnMouseDown",...)
  13.   end
  14.  
  15.   local function ModelOnMouseUp(...)
  16.     print("ModelOnMouseUp",...)
  17.   end
  18.  
  19.   local function CreateModel(parent,id)
  20.     local m = CreateFrame("PlayerModel", nil, parent)
  21.     m.id = id
  22.     m.name = "model"..id
  23.     m:SetScript("OnMouseDown", ModelOnMouseDown)
  24.     m:SetScript("OnMouseUp", ModelOnMouseUp)
  25.   end
  26.  
  27.  
  28.   local frame = CreateFrame("Frame")
  29.  
  30.   frame.models = {}
  31.  
  32.   for i=1, 50 do
  33.     frame.models[i] = CreateModel(frame,i)
  34.   end

object:Function variant

Lua Code:
  1. local frame = CreateFrame("Frame")
  2.    
  3.   function frame:ResetAllModels
  4.     for i, model in pairs(self.models) do
  5.       model:Reset()
  6.     end
  7.   end    
  8.    
  9.   frame.models = {}
  10.  
  11.   --prototype
  12.   frame.modelPrototype = {}
  13.  
  14.   function modelPrototype:Reset(...)
  15.     print("Reset",...)
  16.   end
  17.  
  18.   function modelPrototype:OnMouseDown(...)
  19.     print("OnMouseDown",...)
  20.   end
  21.  
  22.   function modelPrototype:OnMouseUp(...)
  23.     print("OnMouseUp",...)
  24.   end
  25.  
  26.   function frame:CreateModel(id)
  27.     local m = CreateFrame("PlayerModel", nil, self)
  28.     m.id = id
  29.     m.name = "model"..id
  30.     for k, v in pairs(self.modelPrototype) do
  31.       m[k] = v
  32.     end
  33.     m:SetScript("OnMouseDown", m.OnMouseDown)
  34.     m:SetScript("OnMouseUp", m.OnMouseUp)
  35.   end  
  36.  
  37.   for i=1, 50 do
  38.     frame.models[i] = frame:CreateModel(i)
  39.   end

What I'm asking for is the following. If I add a function to an object...does it produce multiple copies of that function or is it by reference?

Using a local function set has the benefit that the function is only defined once but most of the time you need to add self as an argument which you do not need on object functions.

Well...event handler functions will still use self as an argument.

What do you pick and why?
__________________
| Simple is beautiful.
| WoWI AddOns | GitHub | Zork (WoW)

"I wonder what the non-pathetic people are doing tonight?" - Rajesh Koothrappali (The Big Bang Theory)
  Reply With Quote