View Single Post
03-29-24, 11:02 PM   #4
SDPhantom
A Pyroguard Emberseer
 
SDPhantom's Avatar
AddOn Author - Click to view addons
Join Date: Jul 2006
Posts: 2,333
Originally Posted by Codger View Post
Lua Code:
  1. local frame1 = {}
  2. myAddon.frame1 = frame1

I'm guessing it's another way of setting up a namespace?
On the surface, this is just storing one table into another and keeping a local reference to it. Taking the rest of the message into account, I'm assuming the real question is, "What is the 'local reference' for?"

A local used in this way is acting as a cache as it's quicker to access than trying to grab it from the table again. Trying to grab anything from a table is known as an "index operation". Just like any other operation, this takes time, which can add up. In the grand scheme of things, doing this isn't going to cause a noticeable effect unless the affected code is running very frequently, like in loops, OnUpdate scripts, or combat log events.



Originally Posted by Codger View Post
What I am doing in an addon is:

Lua Code:
  1. local addonName, addonTable = ...
  2. function addonTable:doSomething()

which requires me to preface everywhere I use doSomething() with addonTable.
Curious if this is a better way?
The equivalent to implementing it in this code would be either of the following.
Lua Code:
  1. local addonName, addonTable = ...
  2.  
  3. local function doSomething(self)
  4. end
  5.  
  6. addonTable.doSomething = doSomething
-or-
Lua Code:
  1. local addonName, addonTable = ...
  2.  
  3. function addonTable:doSomething()
  4. end
  5.  
  6. local doSomething = addonTable.doSomething
The first one may be used if you're defining a function that is also used in the same file, then have a chunk exporting your local definitions to your addon table.
The second one is more useful if the function was defined in another file and you want to create a local reference for speed.



Keep in mind:
A call v:name(args) is syntactic sugar for v.name(v,args), except that v is evaluated only once.
-Lua 5.1 Reference Manual - (§2.5.8) Function Calls

The colon syntax is used for defining methods, that is, functions that have an implicit extra parameter self. Thus, the statement
function t.a.b.c:f (params) body end
is syntactic sugar for
t.a.b.c.f = function (self, params) body end
-Lua 5.1 Reference Manual - (§2.5.9) Function Definitions

The dot notation better reflects how the function exists in memory and the colon notation is a modifier on how to define or call it. There's no way to use the colon notation when calling from or defining as a local.
__________________
WoWInterface AddOns
"All I want is a pretty girl, a decent meal, and the right to shoot lightning at fools."
-Anders (Dragon Age: Origins - Awakening)

Last edited by SDPhantom : 03-29-24 at 11:39 PM.
  Reply With Quote