Lua教程

Lua极简入门(四)——条件判断

2019-10-20  本文已影响0人  李小磊_0867

表达式

表达式是条件判断的基础,Lua的表达式同其他语言类似,只是表示方式上有一些变化。其表达式主要分为如下几种

条件判断

条件语句是依据给定的条件进行判断,如果条件满足,则执行分支语句,当不满足时,执行另外得分支语句。正是因为条件判断语句,才使得各种任务和业务得以实现,条件判断也是业务程序实现的基石。


比如:对于会员来说,年底给会员发送春节短信,当会员消费超过一千时,发送红包,使用if语句实现:
userConsume = 700

if userConsume >= 1000 then
    print("send a gift to user")
end

print("blessing sms")
-->> blessing sms

如果if条件判断为true,则执行thenend之间的语句,否则就跳过。可以给if添加else语句,这样就会出现两个不同分支,满足true,则执行if语句,否则就执行else语句。

userConsume = 700

if userConsume >= 1000 then
    print("send a gift to user")
else
    print("your consume is not enough")
end

print("blessing sms")

当会员制度细节更具体时,需要嵌套if完成,Lua中提供了elseif,可以实现嵌套if的工作:

userConsume = 800

if userConsume >= 500 then
    print("send a 10 yuan gift to user")
elseif userConsume >= 800 then
    print("send a 20 yuan gift to user")
elseif userConsume >= 1000 then
    print("send a 30 yuan gift to user")
else
    print("your consume is not enough")
end

print("blessing sms")

在条件判断的执行过程中,当有一个if命中,则后续的条件判断都不再执行,因此上述语句中,发送了10元红包。条件判断需要根据具体的需求进行调整,使得业务逻辑不存在问题。

条件判断的语法规则:

if <条件判断1> then
    <执行语句1>
elseif <条件判断2> then
    <执行语句2>
[elseif...]
else
    <else执行语句>
end
上一篇 下一篇

猜你喜欢

热点阅读