Lua学习(三)语句

1、赋值语句
a = 1
a,b = 10, 2*x   (多重赋值)
x,y,z=1,2       (x=1,y=2,z=nil)
x,y = y,x       (交换x,y值)

2、局部变量和块(block)
局部变量:用 local 定义,作用域仅限于声明它的那个块

块:可以是一个控制结构体,一个函数体,一个程序块chunk(文件或文本串)
x = 10        --全局变量
local i = 1   --局部变量

while i <= x do
    local x = i*20       --while循环体中的局部变量x
    print(x)             --2,4,6,8...
    i = i + 1
end

if i > 20 then 
    local x              --then中的局部变量
    x = 20
    print(x+2)           --22
else
    print(x)             --全局变量10
end

print(x)                 --全局变量10

尽可能使用局部变量:
  1:避免命名冲突
  2:访问局部变量的速度比全局变量快


3、控制结构
  1、if语句
if conditions then
    then-part
end

if conditions then
    then-part
else
    else-part
end

if conditions then
    then-part
elseif condition then
    elseif-part
..
else
    else-part
end

  2、while语句
while conditions do
    do-part
end

  3、repeat语句
repeat
  repeat-part
util conditions

  4、数值for
for var=exp1,exp2,exp3 do
    statements
end

注意:
1 控制变量var被自动声明为for的局部变量
2 不要在循环过程中修改控制变量值,会导致结果不可控


  5、泛型for
for i,v in pairs(t) do
    statements
end
i是table t的索引,v是table t中,索引为i的元素值。pairs-遍历数组的迭代器

4、break和return
break用于结束一个循环
return用于函数结果返回

猜你喜欢

转载自room-bb.iteye.com/blog/2294110