WoW:Lua variable scoping: Difference between revisions

m
→‎Complex Scope: Corrected a mistake in the example
(add breadcrumb)
m (→‎Complex Scope: Corrected a mistake in the example)
Line 137: Line 137:
   end
   end
   n = 0;                      -- Global variable
   n = 0;                      -- Global variable
  foo(1);
   function foo(n)            -- In comments, assuming parameter n = 1
   function foo(n)            -- In comments, assuming parameter n = 1
       p(n);                    -- Prints 1
       p(n);                    -- Prints 1
Line 144: Line 143:
       if (true) then          -- Entering a new code block
       if (true) then          -- Entering a new code block
         p(n);                -- Prints 2
         p(n);                -- Prints 2
         local n = 10;        -- Creates a more local "n," now
         local n = 15;        -- Creates a more local "n," now
         p(n);                -- Prints 10
         p(n);                -- Prints 15
         for x = 1, 10 do      -- Note x is also a local variable now, not accessible outside for block
         for x = 1, 10 do      -- Note x is also a local variable now, not accessible outside for block
             -- Note each iteration is a separate block!
             -- Note each iteration is a separate block!
             p(n);              -- Prints 10 EVERY TIME (even on 2nd+ loop)
             p(n);              -- Prints 15 EVERY TIME (even on 2nd+ loop)
             local n = x;
             local n = x;
             p(n);              -- Prints 1,2,...,10 (depending on iteration)
             p(n);              -- Prints 1,2,...,10 (depending on iteration)
         end
         end
         p(n);                -- Prints 10 (n in for block is out of scope)
         p(n);                -- Prints 15 (n in for block is out of scope)
         p(x);                -- Prints nil (x is local to the for block)
         p(x);                -- Prints nil (x is local to the for block)
       end
       end
       p(n);                    -- Prints 2
       p(n);                    -- Prints 2
   end
   end
  foo(1);
   p(n);                      -- Prints 0 (using global n, as there is no local n)
   p(n);                      -- Prints 0 (using global n, as there is no local n)