查看: 36|回复: 0

Lua 入门教程——流程控制

[复制链接]

48

主题

75

回帖

1991

积分

金牌会员

积分
1991
QQ
发表于 2026-5-25 17:52:47 | 显示全部楼层 |阅读模式
1. if 条件判断
local score = 85

if score >= 90 then
    print("优秀")
elseif score >= 80 then  -- 注意:是 elseif 不是 else if
    print("良好")
elseif score >= 60 then
    print("及格")
else
    print("不及格")
end
2. while 循环
local i = 1
while i <= 5 do
    print(i)
    i = i + 1
end
-- 输出:1 2 3 4 5
3. for 循环
-- 数值 for 循环(起始, 结束, 步长)
for i = 1, 10, 2 do  -- 步长默认为 1
    print(i)
end
-- 输出:1 3 5 7 9

-- 泛型 for 循环(遍历表)
local fruits = {"苹果", "香蕉", "橙子"}
for index, value in ipairs(fruits) do
    print(index, value)
end

local person = {name = "张三", age = 25}
for key, value in pairs(person) do
    print(key, value)
end
4. repeat-until 循环(先执行后判断)
local count = 1
repeat
    print(count)
    count = count + 1
until count > 5
-- 输出:1 2 3 4 5
5. 循环控制
-- break:退出循环
for i = 1, 10 do
    if i == 5 then
        break
    end
    print(i)
end
-- 输出:1 2 3 4

-- goto:跳转到标签(谨慎使用)
::continue::
for i = 1, 10 do
    if i % 2 == 0 then
        goto continue  -- 跳过偶数
    end
    print(i)
end
-- 输出:1 3 5 7 9

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

快速回复 返回顶部 返回列表