Lua elseif 多分支

Alexer 发布于 阅读:15 速查

Lua 里做多分支判断就用 if ... elseif ... else ... end。条件从上往下依次判断,谁先为真就执行谁的分支,执行完整个结构就结束,后面的条件不再看。

写法上几个硬点:elseif 是一个词,中间不能空格;每个分支的条件后面必须跟 then;else 不带条件,也可以不写;最后必须用 end 收尾。

local score = 85

if score >= 90 then
    print("优秀")
elseif score >= 80 then      -- 条件写在这里,后面跟 then
    print("良好")
elseif score >= 60 then
    print("及格")
else                         -- 兜底分支,可省略
    print("不及格")
end                          -- 结束必须写

注意 else if 中间带空格不是多分支写法,那是嵌套的 if,会要求多配一个 end,容易对不上。条件顺序要按从严格到宽松排,比如上面先判断 90 再判断 80,顺序反了后面的分支就永远进不去。

语法基础 Lua 脚本基础