Defining functions
Hello
I'm fiddling around with some addons and I see people are using: Code:
GetHealthText = function(unit, cur, max) What is the difference between these 2? |
The most common is using "function name(args)"
Also you can use "local" as prefix to limit the scope, otherwise your examples create global functions usable by all addons, and it might even write over already existing functions like that. Just be careful. :) |
Thanks
Yeah I've had my code do bad things to other addons:p But they do the exact same thing? |
Both of your examples would work exactly the same. The only time there would be a difference between them is if they were declared as local and were for a recursive function.
Code:
local function TestA(x) Code:
local TestB |
Everyone beat me to the punch ;)
|
Also when using a local function you can play with the variables and store them in unusual ways.
Like for instance this snippet. I've used similar to alter the default UnitName returned values to always include the realm, instead of nil when the unit is on the same realm as you. Note this is old code and with recent realm changes it might not work as expected. :) Code:
local UnitName I doubt you'd notice much performance improvement between this version and simply using "local name, realm = _G.UnitName(...)" - maybe if your testing scope is large enough you might notice some time differences. :) |
Alright, thanks for explaining so thoroughly.
I got confused when these 2 methods were mixed in the same addon, guess it's because they've copied bits and pieces from other places. |
There are several other ways you declare a function, so if you experience issues when coding your own do come back and ask.
|
Will do, you've been very helpful.
|
Quote:
Yes, the _G upvalue there is redundant and useless clutter, unless you are looking up globals you are constructing dynamically (eg _G["PartyFrame"..i.."HealthBar"]). In your example, you would be better off just upvaluing UnitName directly, or not bothering to upvalue at all (unless you're running that code inside an OnUpdate script or CLEU handler or something similarly spammy). |
Quote:
|
All times are GMT -6. The time now is 03:54 PM. |
vBulletin © 2024, Jelsoft Enterprises Ltd
© 2004 - 2022 MMOUI