--- Scope ---
j = 10 -- global variable
local i = 1 -- local variable
-- Unlike global variables, local variables have their scope limited to the block where they are declared.
-- A block is the body of a control structure, the body of a function, or a chunk.
print("----Local Variables and Blocks----")
x = 10 -- global variable
local i = 1 -- local to the chunk
while i<=x do
local x = i*2 -- local to the while body
print(x) --> 2, 4, 6, 8, ...
i = i + 1
end
print("----Global Variables and Blocks----")
if i > 20 then
local x -- local to the "then" body
x = 20
print(x + 2)
else
print(x) --> 10 (the global one)
end
print(x) --> 10 (the global one)
print("----用 do-end 明確地界定一個block----")
-- 用 do-end 明確地界定一個block。 when you need finer control over the scope of one or more local variables:
a = 5
b = 10
c = 3.2
do
local a2 = 2*a
local d = math.sqrt(b^2 - 4*a*c)
x1 = (-b + d)/a2
x2 = (-b - d)/a2
end -- scope of `a2' and `d' ends here
print(x1, x2)
-- A common idiom in Lua is
-- local foo = foo
-- This code creates a local variable, foo, and initializes it with the value of the global variable foo. That idiom is useful when the chunk needs to preserve the original value of foo even if later some other function changes the value of the global foo; it also speeds up access to foo.
-- Once the end of the scope is reached the values in that scope are no longer accessable
print("----Variables have different scopes----")
function foo()
local a = 10
end
print(a) --nil
local isAlive = true
if isAlive then
local a = 10
end
print(a) --nil
---[[ Loops ]]---
---[[ While Loop ]]---
-- while (condition) do
-- print ("Do something")
-- end
print("----While Loop----")
local i = 8
local count = 0
while i <= 10 do
count = count + 1
i = i + 1
print("count is " .. i)
end
print("----For Loop----")
count = 0
for i=1, 5 do
count = count + 1
print("count is " .. count)
end
print("----Nested Loops----")
local count = 0
for a=1, 10 do
for b=1, 10 do
count = count + 1
end
end
print(count) -- 100
---[[ Repeat ... Until ]]---
-- repeat
-- statements
-- until(condition)
To embed this program on your website, copy the following code and paste it into your website's HTML: