Lua 三目运算符

前言

在C#中有三目运算符:

a ? b : c;     //a为真,表达式的值为b,否则表达式的值为c 

在Lua 原生的语义并没有实现三目运算,一般是通过逻辑运算符 and 和 or 来模拟三目运算符的。

基础知识

Lua语言中的逻辑运算符有and、or和not,and 和 or 都是用的短路求值,即与第二操作数无关。
Lua中将 false 或 nil 视为假,而将除此之外的任何东西视为真。
对于and运算符,如果第一个条件为假,则返回第一个操作数,否则返回第二个操作数(一假即假)
对于or运算符,如果第一个条件为真,则返回第一个操作数,否则返回第二个操作数(一真即真)
例如:

local a = 2>1 and 3         -- a = 3
local b = 2<1 and 3         -- b = false
local c = 2>1 or 3          -- c = true
local d = 2<1 or 3          -- d = 3
print(a,b,c,d)

Lua三目运算

a and b or c

local e = 2>1 and 3 or 4    -- e = 3(2>1 and 3 => 3, 3 or 4 => 3)
local f = 2<1 and 3 or 4    -- f = 4
print(e, f)

Lua中三目运算符陷阱

按照三目运算符的规则,lua的三目运算符可以写成:a and b or c

  • b = true
    • a = true
      • a and b –> true
      • b or c –> b
    • a = false
      • a and b –> false
      • b or c –> c
  • b = false
    • a = true
      • a and b –> false
      • b or c –> c
    • a = false
      • a and b –> false
      • b or c –> c

这样就会导致,b为false时,三目运算符是无效的。

解决办法

在三目运算符 a and b or c 表达式外边包装一层table
b表达式的外边包装一层table,写成{b}的形式,返回时再写成{b}[1]的形式就可以,那么整体的表达式就变成:(a and {b} or {c})[1]
总结:
当程序员编码时候确认b为真,那么就用a and b or c,简单粗暴。
不确定b是否为真时,使用 (a and {b} or {c})[1] ,逻辑严谨。

-- 陷阱
local g = 2>1 and false or true             -- g = true
local h = 2<1 and false or true             -- h = true
print(g, h)

-- 解决方法
local x = (2>1 and {
    
    false} or {
    
    true})[1]    -- x = false
local y = (2<1 and {
    
    false} or {
    
    true})[1]    -- y = true    
print(x, y)

猜你喜欢

转载自blog.csdn.net/weixin_45136016/article/details/126352528
今日推荐