View Single Post
04-06-22, 09:51 AM   #6
SDPhantom
A Pyroguard Emberseer
 
SDPhantom's Avatar
AddOn Author - Click to view addons
Join Date: Jul 2006
Posts: 2,325
It's good practice to make local functions instead of global ones whenever you can. It'll help you avoid name collisions like these in the global table.

As with any local variable, you need to define the variable before you reference it elsewhere, even if you have to temporarily leave it nil. Otherwise, Lua will try to look for it in the global table instead.



Option 1: Define the function before any reference you make to it.
Lua Code:
  1. local function MyFunction()
  2. --  Do stuff
  3. end
  4.  
  5. --  Other functions that call MyFunction() should be placed after it

Option 2: Mark the function name as a local at the top of your Lua file.
Lua Code:
  1. local MyFunction;-- Function "prototype"
  2.  
  3. --  You can place your functions in any order you want as long as they appear after the "local" statement above
  4.  
  5. function MyFunction()-- Lua will see this name is defined as a local at the top of the file and will place it in that scope instead of the global table
  6. --  Do stuff
  7. end



Option 2 is an easier way to convert existing code to use locals, but I consider Option 1 to be cleaner and should be considered when writing new code.

PS: Keep in mind your addon shares the global table with all other addons too. It's suggested for every global you use (including frame and region names) are prefixed with the name of your addon to also help prevent name collisions.
__________________
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 : 04-06-22 at 09:55 AM.
  Reply With Quote