返回首页

教程导航

返回首页

🏷️ 标签(1)

🗂️ 分类(1)

第 5 章 控制流

第 5 章 控制流

控制流决定程序在什么条件下执行哪些语句。Lua 提供条件分支、循环、break 和 goto。

if 与 elseif

基本语法:

local score = 82

if score >= 90 then
  print("优秀")
elseif score >= 60 then
  print("通过")
else
  print("未通过")
end

条件表达式只要不是 false 或 nil 就为真。不要把其他语言的“非零才为真”规则带进 Lua,因为 0 在 Lua 中为真。

多条件判断

local function classify(value)
  if type(value) ~= "number" then
    return "not-number"
  end

  if value < 0 then
    return "negative"
  elseif value == 0 then
    return "zero"
  elseif math.type(value) == "integer" then
    return "positive-integer"
  else
    return "positive-float"
  end
end

先处理不满足前置条件的输入,可以减少嵌套层级。

while 与 repeat

while

local count = 3

while count > 0 do
  print(count)
  count = count - 1
end

repeat

repeat 至少执行一次,直到条件为真:

local input

repeat
  io.write("输入 positive: ")
  input = tonumber(io.read())
until input and input > 0

print("你输入了", input)

循环变量必须在循环体内更新。使用 while true do 时要保证每条路径都有退出条件。

数值 for 循环

for index = 1, 5 do
  print(index)
end

for index = 10, 1, -2 do
  print(index)
end

起始值、结束值和步长在循环开始前求值。循环变量是局部变量,不应在循环外依赖它。

常见求和

local function sum(first, last)
  local total = 0
  for value = first, last do
    total = total + value
  end
  return total
end

print(sum(1, 100))

break 与 goto

break 立即退出当前循环:

for index = 1, 10 do
  if index == 4 then
    break
  end
  print(index)
end

goto 跳转到同一函数内的标签。它适合跳出多层循环,但不应滥用:

for row = 1, 3 do
  for column = 1, 3 do
    if row * column == 6 then
      goto found
    end
  end
end

::found::
print("找到组合")

不能跳入局部变量的作用域。大多数场景用函数提前返回比多层 goto 更清晰。

常见控制流模式

提前返回

local function normalizeName(name)
  if type(name) ~= "string" then
    return nil, "name 必须是字符串"
  end

  name = name:match("^%s*(.-)%s*$")
  if name == "" then
    return nil, "name 不能为空"
  end

  return name
end

状态机循环

local state = "start"

while state ~= "done" do
  if state == "start" then
    print("准备数据")
    state = "process"
  elseif state == "process" then
    print("处理数据")
    state = "done"
  end
end

状态机把复杂流程拆成明确状态,便于测试和扩展。

上一章:运算符与表达式 | 下一章:函数