0Pricing
Lua Academy · 课时

if、elseif 和 else 语句

使用 Lua 的 if/elseif/else 语法编写条件分支逻辑。

if、elseif 和 else 语句 是 CoddyKit 上的免费 Lua Academy 课时。 这是第 1 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Lua Academy 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Lua Academy 课程共包含 4 节课。

基本 if 语句

if 语句会计算一个条件,并在条件为真值时执行其代码块。在 Lua 中,只有 false 和 nil 是假值;其他所有值(包括 0 和 "")都是真值。请使用 end 结束代码块。

local score = 85

if score >= 90 then
  print("A grade")
end

if score >= 60 then
  print("Passing")   -- prints
end

if 0 then
  print("0 is truthy!")  -- prints in Lua
end

if/elseif/else

使用 elseif 串联多个条件,并使用 else 提供备用分支。Lua 会从上到下计算条件,只执行第一个匹配的分支。与其他语言中的 switch/case 不同,Lua 的 elseif 是一个单独的关键字(不是 else if)。

local score = 75

if score >= 90 then
  print("A")
elseif score >= 80 then
  print("B")
elseif score >= 70 then
  print("C")   -- prints
elseif score >= 60 then
  print("D")
else
  print("F")
end

条件中的逻辑运算符

Lua 使用 and、or 和 not 作为逻辑运算符。它们具有短路特性:and 返回第一个假值,或者返回最后一个值;or 返回第一个真值,或者返回最后一个值。这使得默认值惯用模式成为可能。

local age = 25
local hasID = true

if age >= 18 and hasID then
  print("Entry allowed")
end

-- or for defaults
local name = nil
local display = name or "Guest"
print(display)   -- Guest

使用 and/or 的三元表达式惯用写法

Lua 没有三元运算符,但可以使用 and/or 模式近似实现:condition and trueVal or falseVal。只要 trueVal 不是 false 或 nil,此模式就能正常工作。若要实现更安全的三元逻辑,请使用内联 if 函数。

local x = 10
local label = (x > 5) and "big" or "small"
print(label)   -- big

-- Safe ternary function
local function ternary(cond, t, f)
  if cond then return t else return f end
end
print(ternary(false, "yes", "no"))  -- no

嵌套 if 语句

您可以在其他分支中嵌套 if 语句。每个嵌套代码块都需要各自的 end。深层嵌套通常表明可以使用提前返回或守卫子句来简化逻辑。

local loggedIn = true
local isAdmin = false

if loggedIn then
  if isAdmin then
    print("Admin dashboard")
  else
    print("User dashboard")  -- prints
  end
else
  print("Login required")
end

守卫子句

守卫子句是在函数开头处理无效情况或边界情况的提前返回语句,可以减少嵌套。这种模式能让“正常流程”代码保持不缩进,更易于阅读。

local function processAge(age)
  if type(age) ~= "number" then
    return nil, "age must be a number"
  end
  if age < 0 then
    return nil, "age cannot be negative"
  end
  -- happy path
  return math.floor(age)
end

print(processAge(25.7))   -- 25
print(processAge(-1))     -- nil  age cannot be negative

比较值

Lua 的比较运算符包括:==(相等)、~=(不相等)、<、>、<=、>=。请注意:~= 是 Lua 的“不相等”运算符,不是 !=。字符串比较使用字典序。您不能直接比较字符串和数字。

print(1 == 1)      -- true
print(1 ~= 2)      -- true
print("abc" < "abd")  -- true (lexicographic)
print("10" == 10)  -- false (different types)

-- Safe nil check
local val = nil
if val == nil then
  print("no value")
end

字符串相等性

当且仅当两个字符串的字节内容和长度都相同时,它们在 Lua 中才相等。Lua 会驻留字符串,因此相等的字符串通常指向同一块内存,使得 == 可以快速进行指针比较。请不要使用 is 或引用相等性来比较字符串——== 始终按值进行比较。

local s1 = "hello"
local s2 = "hel" .. "lo"

print(s1 == s2)     -- true (same content)
print(s1 == "Hello") -- false (case sensitive)

-- Check for empty string
local name = ""
if name == "" or name == nil then
  print("name is empty or nil")
end

表与函数的比较

表和函数按引用比较,而不是按内容比较。两个内容相同但彼此不同的表字面量不相等,除非它们是同一个对象。您可以使用 __eq 等元方法为表定义自定义相等规则。

local t1 = {1, 2, 3}
local t2 = {1, 2, 3}
local t3 = t1

print(t1 == t2)   -- false (different objects)
print(t1 == t3)   -- true (same reference)

local f1 = function() end
local f2 = function() end
print(f1 == f2)   -- false

惯用模式

Lua 条件语句中的常见惯用写法包括:使用 assert() 验证前置条件,使用 and/or 技巧提供简短的默认值,以及避免使用双重否定(not not x)将任意值转换为布尔值。

-- assert pattern
local function sqrt(n)
  assert(n >= 0, "sqrt of negative")
  return math.sqrt(n)
end

-- Convert to boolean
local val = 42
local boolVal = not not val
print(boolVal)   -- true

-- Default parameter
local function greet(name)
  name = name or "World"
  print("Hello, " .. name)
end
greet()          -- Hello, World

快速检查

Lua 中哪些值是假值?

回顾:条件语句

总结:

  • if ... elseif ... else ... end——完整的分支形式
  • 只有 nil 和 false 是假值
  • and/or 会短路,并返回操作数的值
  • ~= 是 Lua 中的“不相等”运算符(不是 !=)
  • 表和函数按引用比较,字符串按值比较
  • 使用守卫子句减少嵌套

常见问题解答

「if、elseif 和 else 语句」课时是免费的吗?

是的 — 「if、elseif 和 else 语句」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Lua Academy 课程的其余内容,请升级到 CoddyKit PRO。 Lua Academy 课程共包含 4 节课。

「if、elseif 和 else 语句」这节课中我会学到什么?

使用 Lua 的 if/elseif/else 语法编写条件分支逻辑。 你通过在浏览器中直接运行的动手代码来练习 Lua Academy,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 Lua Academy 需要有经验吗?

无需任何先前经验。CoddyKit 上的 Lua Academy 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 1 节课,共 4 节。

「if、elseif 和 else 语句」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 Lua Academy 课中编写并运行代码吗?

能。每节 Lua Academy 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. if、elseif 和 else 语句
  2. while 和 repeat-until 循环
  3. 数值 for 循环
  4. 泛型 for 和 break
← 返回 Lua Academy