lua语句结构2--局部变量

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)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值