Lua学习笔记:流程与循环

流程语句

if 语句

if (true) then
    print("Yes")
else
    print("No")
end

输出结果: Yes

elseif 语句

if (false) then
    print("1.Yes")
elseif (true) then
    print("2.Yes")
end

输出结果: 2.Yes

循环语句

for循环

普通for循环
普通的for循环一共3个参数分别为: 初始条件,结果,执行计算(默认是+1)

-- for循环 三个参数分别为:初始条件,结果,执行计算(默认是+1)
for i = 0, 3 do       -- 没写默认+1
     print("0到3每次+1:", i)
     end 
for i = 3, 0, -1 do 
     print("3到0每次-1:", i)
     end 
for i = 5, 3, -1 do 
    print("5到3每次-1:", i) 
end 
for i = 1, 10, 3 do 
    print("1到10每次+3:", i) 
end 

输出结果:

03每次+10
03每次+11
03每次+12
03每次+13

30每次-13
30每次-12
30每次-11
30每次-10

53每次-15
53每次-14
53每次-13

110每次+31
110每次+34
110每次+37
110每次+310

泛型for循环

-- 泛型for循环 ,ipairs:数组迭代器
a = {
    
    "one", "two", "three"}
for i, v in ipairs(a) do -- > 可以当作C#中的foreach()            
    print(i, v)
end

输出结果

1	one
2	two
3	three

while 循环

-- while 循环
i = 0
while (i < 3) -- >条件为假结束循环
do
    i = 1 + i;
    print(i)
end

输出结果

1
2
3

repeat … unitl循环

其实和C里面的 do…while循环差不多,先循环一次再判断条件

-- repeat .. unitl循环
a = 0
repeat
    print("a的值为:", a)
    a = a + 1
until (a > 3) -- >条件为真就跳出

输出结果

a的值为:	0
a的值为:	1
a的值为:	2
a的值为:	3

循环控制语句

break关键字

作用:跳出循环

i = 0
while (i < 5) 
do
    if (i == 3) then 
        print("loop over")
        break -- 执行时会退出当前循环
    end
    i = 1 + i;
    print(i)
end

输出结果

1
2
3
loop over

goto 和 标签( ::X:: )

goto 要和 标签一起使用
goto <标签位置> 会让代码再次运行到标签位置,从而实现C# continue 一样的效果

-- goto 语句  ::XX:: 为标签写法
local a = 1
::label::
print("--- goto label ---")
a = a + 1
if a < 3 then
    goto label -- a 小于 3 的时候跳转到标签 label(代码会再次从第3行开始运行)
end


-- 实现continue
for i = 1, 3 do
    if i <= 2 then
        print(i, "yes continue")
        goto continue
    end
    print(i, " no continue")
    ::continue::
    print([[I'm end]])
end

输出结果

--- goto label ---
--- goto label ---
1	yes continue
i'm end
2	yes continue
i'm end
3	 no continue
i'm end

猜你喜欢

转载自blog.csdn.net/wa36d/article/details/127356312
今日推荐