没有类型的Lua条件

时间:2017-10-24 00:25:58

标签: lua null conditional conditional-statements

问题(S)

Lua

local a = b or 0
local a = b and 1 or 0

其中b可以是任何类型。

代码行之间有什么区别? 在什么情况下我会使用其中一个?

上下文

我必须将现有的Lua代码移植到另一个服务,我遇到了一个问题,理解为什么在代码的某些部分(我不是Lua开发人员),变量得到了分配给代码的一个和其他部分,变量被分配给另一个。右侧的变量是输入参数,我无法知道预期的类型。

我尝试了什么

我在网上查看Lua文档,我无法找到任何明确的答案。我运行了自己的测试:

local a1;
print(type(a1))               -- nil
local b1 = a1 or 0            
print(b1 .. " " .. type(b1))  -- 0 number
local c1 = a1 and 1 or 0
print(c1 .. " " .. type(c1))  -- 0 number

local a2 = 5
print(type(a2))               -- number
local b2 = a2 or 0          
print(b2 .. " " .. type(b2))  -- 5 number
local c2 = a2 and 1 or 0
print(c2 .. " " .. type(c2))  -- 1 number

local a3 = 0
print(type(a3))               -- number
local b3 = a3 or 0          
print(b3 .. " " .. type(b3))  -- 0 number
local c3 = a3 and 1 or 0
print(c3 .. " " .. type(c3))  -- 1 number

local a4 = false
print(type(a4))               -- boolean
local b4 = a4 or 0
print(b4 .. " " .. type(b4))  -- 0 number
local c4 = a4 and 1 or 0
print(c4 .. " " .. type(c4))  -- 0 number

local a5 = true
print(type(a5))               -- boolean
local b5 = a5 or 0
print(b5 .. " " .. type(b5))  -- error, concatenating boolean to string
local c5 = a5 and 1 or 0
print(c5 .. " " .. type(c5))  -- 1 number

local a6 = "str"
print(type(a6))               -- string
local b6 = a6 or 0
print(b6 .. " " .. type(b6))  -- str string
local c6 = a6 and 1 or 0
print(c6 .. " " .. type(c6))  -- 1 number

local a7 = ""
print(type(a7))               -- string
local b7 = a7 or 0
print(b7 .. " " .. type(b7))  --  string
local c7 = a7 and 1 or 0
print(c7 .. " " .. type(c7))  -- 1 number

在我看来,具有and条件的代码行的唯一用例是b是布尔值或零值类型而a应该导致0 { {1}}为bnil,当b为false时为1。

1 个答案:

答案 0 :(得分:2)

在Lua中,这些是选择算子,具有短路评估。

falsenil是“假的”;任何其他价值都是“真实的”。除了“falsey”之外,操作数类型无关紧要,结果类型不一定是"boolean"

  • or选择(返回)第一个真正的操作数。

  • and选择第一个操作数(如果为false),否则选择第二个操作数。它的优先级高于or

这导致了几个习语:

b or 0 -- default to 0
t = t or {} -- existing or new, empty table
b and 1 or 0 -- coerce to 1, defaulting to 0

你的两个例子之间的区别是第二个强制为1,而第一个让“truthy”b为。