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 | ||
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 = | local n = 15; -- Creates a more local "n," now | ||
p(n); -- Prints | 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 | 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 | 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) | ||