1.局部变量以及块(Block)
除了全局变量之外,lua语句还支持局部变量,使用(local关键字)。
局部变量的作用于局限于他们声明的语句块中:比如函数体,也比如控制语句中,以及chunk(the file or string with the code where the variable is declared)
j = 10 --global variable
local i = 1 ---local variable
x = 10
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
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
如果没有初始赋值,将会给初始值赋为nil。
local a, b = 1,10
if a<b then
print(a) -->1
local a --‘nil’ is implicit
print(a) --> nil
end
print(a,b) --> 1 10
也可以使用do-end 显示一个代码块(block),如下:
do
local a2 = 2*a
local d = 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)