WoW:Lua variable scoping: Difference between revisions

m (Corrected spelling/grammar)
Line 98: Line 98:


   function foo(bar, baz)
   function foo(bar, baz)
       DEFAULT_CHAT_FRAME:AddMessage(tostring(bar)..", "..tostring(baz));
      local n = bar + baz;
       DEFAULT_CHAT_FRAME:AddMessage(tostring(bar).." + "..tostring(baz).." = "..tostring(n));
   end
   end
   foo(1,2)                                                          -- Prints 1, 2
   foo(1,2)                                                          -- Prints 1 + 2 = 3
   DEFAULT_CHAT_FRAME:AddMessage(tostring(bar)..", "..tostring(baz)); -- Prints nil, nil (out of scope)
   DEFAULT_CHAT_FRAME:AddMessage(tostring(bar).." + "..tostring(baz).." = "..tostring(n)); -- Prints nil + nil = nil (out of scope)
 
Function-local parameter variables are not directly declared by the author (though they are essentially created by the author, as the author created the function), but they operate in the same manner. They are still local variables and should be treated as such. Besides the parameters the author can still explicitly declare local variables inside the function that are function-local variables.


Function-local variables are not directly declared by the author (though they are essentially created by the author, as the author created the function), but they operate in the same manner. They are still local variables and should be treated as such.
 
=== Block-local variables ===
=== Block-local variables ===
Block-local variables, like their name suggests, are variables which are accessible only within the code block in which they are defined. These are often used for simplistic names which only need to be quickly accessed within that function and nowhere else. These are often counters or temporary variables which are no longer necessary once the function returns. Take the following function, for example, which adds two numbers together:
Block-local variables, like their name suggests, are variables which are accessible only within the code block in which they are defined. These are often used for simplistic names which only need to be quickly accessed within that function and nowhere else. These are often counters or temporary variables which are no longer necessary once the function returns. Take the following function, for example, which adds two numbers together:
Anonymous user