View Single Post
06-25-18, 10:17 AM   #5
myrroddin
A Pyroguard Emberseer
 
myrroddin's Avatar
AddOn Author - Click to view addons
Join Date: Oct 2008
Posts: 1,240
Originally Posted by seyan777 View Post

The question is, can you change the value of outer variable even if you declare a new local variable with an outer one's name within a function?
Not easily, if at all. It is easier and recommended to have different names for variables because of this reason. For simplicity's sake, I will rename the variables and add comments.
Lua Code:
  1. local outVar = 1 -- this variable is global scope to the entire file
  2.  
  3. local addonName, pvtTable = ... -- both of these are local to ALL Lua files within the same addon
  4.  
  5. local function TestFunction() -- this function is global scope to the entire file
  6.     -- assign a local variable that has the scope of just this function,
  7.     -- and give it the value of the file's version. Naming is irrelevant
  8.     local outVar = outVar -- value == 1
  9.  
  10.     outVar = 2 -- we are still talking about the local variable, == 2
  11.     -- the global outVar is still == 1 and we haven't overwritten it
  12. end
  13.  
  14. local TestFunction2() -- this is what you want
  15.     local innerVar = outVar -- innerVar == 1
  16.     outVar = 2 -- outVar == 2, no really this time!
  17. end
  18.  
  19. function TestFunction3() -- this function is global across the entirety of WoW (careful!)
  20.     -- global names are 99.99% bad
  21.     -- you have no idea who else named a function or variable exactly the same
  22.     -- which will have conflicts and crashes and unexpected results
  23. end

Last edited by myrroddin : 06-25-18 at 10:21 AM. Reason: Corrected myself
  Reply With Quote