if-else 是我們熟知的一種控制結(jié)構(gòu)。Lua 跟其他語言一樣,提供了 if-else 的控制結(jié)構(gòu)。因?yàn)槭谴蠹沂煜さ恼Z法,本節(jié)只簡單介紹一下它的使用方法。
x = 10
if x > 0 then
print("x is a positive number")
end
運(yùn)行輸出:x is a positive number
x = 10
if x > 0 then
print("x is a positive number")
else
print("x is a non-positive number")
end
運(yùn)行輸出:x is a positive number
score = 90
if score == 100 then
print("Very good!Your score is 100")
elseif score >= 60 then
print("Congratulations, you have passed it,your score greater or equal to 60")
--此處可以添加多個(gè)elseif
else
print("Sorry, you do not pass the exam! ")
end
運(yùn)行輸出:Congratulations, you have passed it,your score greater or equal to 60
與 C 語言的不同之處是 else 與 if 是連在一起的,若將 else 與 if 寫成 "else if" 則相當(dāng)于在 else 里嵌套另一個(gè) if 語句,如下代碼:
score = 0
if score == 100 then
print("Very good!Your score is 100")
elseif score >= 60 then
print("Congratulations, you have passed it,your score greater or equal to 60")
else
if score > 0 then
print("Your score is better than 0")
else
print("My God, your score turned out to be 0")
end --與上一示例代碼不同的是,此處要添加一個(gè)end
end
運(yùn)行輸出:My God, your score turned out to be 0