一天三盒半 发表于 2026-5-25 17:52:47

Lua 入门教程——流程控制

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("不及格")
end2. while 循环
local i = 1
while i <= 5 do
    print(i)
    i = i + 1
end
-- 输出:1 2 3 4 53. 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)
end4. repeat-until 循环(先执行后判断)
local count = 1
repeat
    print(count)
    count = count + 1
until count > 5
-- 输出:1 2 3 4 55. 循环控制
-- 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

页: [1]
查看完整版本: Lua 入门教程——流程控制