x = 10 if x > 0then print("x is a positive number") end
运行输出:x is a positive number
两个分支 if-else 型
1 2 3 4 5 6
x = 10 if x > 0then print("x is a positive number") else print("x is a non-positive number") end
运行输出:x is a positive number
多个分支 if-elseif-else 型
1 2 3 4 5 6 7 8 9
score = 90 if score == 100then print("Very good!Your score is 100") elseif score >= 60then print("Congratulations, you have passed it,your score greater or equal to 60") --此处可以添加多个elseif else print("Sorry, you do not pass the exam! ") end
运行输出:Congratulations, you have passed it,your score greater or equal to 60
与 C 语言的不同之处是 else与if 是连在一起的,若将 else 与 if 写成 “else if” 则相当于在 else 里嵌套另一个if语句,如下代码:
1 2 3 4 5 6 7 8 9 10 11 12
score = 0 if score == 100then print("Very good!Your score is 100") elseif score >= 60then print("Congratulations, you have passed it,your score greater or equal to 60") else if score > 0then print("Your score is better than 0") else print("My God, your score turned out to be 0") end--与上一示例代码不同的是,此处要添加一个end end