Lua“” == true等于“” == false


Lua “”==true equals “”==false

我在理解表达式""==true""==false都如何计算为false时遇到麻烦。

在lua解释器和ilua中尝试以下操作会得到相同的输出:

1
2
3
4
> =""==true
false
> =""==false
false

或执行以下命令:

1
2
3
print(""==true)
print(""==false)
print(""==nil)

产出

1
2
3
4
5
Lua 5.1.4  Copyright (C) 1994-2008 Lua.org, PUC-Rio
false
false
false
>

另一个例子:

1
2
3
4
> =""~=true
true
> =""==false
false

运行以下代码时:

1
2
3
4
5
6
7
if"" then -- if""==true
    print"was true"
end

if not"" then -- if""==false
    print"was not true"
end

输出是(看似不一致)

1
2
3
Lua 5.1.4  Copyright (C) 1994-2008 Lua.org, PUC-Rio
was true
>

正如Lua FAQ所预期的那样

C-like languages regard 0 as equivalent to false, but this is not true
for Lua. Only an explicit false or nil are equivalent to false. When
in doubt, make the condition explicit, e.g. if val == nil then ... end
unless the value is actually boolean.

值如何不等于truefalsenill


除nil和false外,所有Lua值均用作布尔值时均评估为true。这并不意味着评估为true的值等于true。如果要将值v转换为布尔值,请使用not not v


""的类型是字符串,而不是布尔值,因此它不等于truefalse

更笼统地说,当Lua比较两个值时,它将首先测试它们的类型,如果类型不匹配,Lua会立即认为这两个值不相等。

当用作控制表达式时,Lua中唯一的假值是falsenil,其他所有值均被评估为真值。一些常见的混淆包括数字0,空字符串"",字符串"0",它们都是真值。再次注意,falsenil不相等,因为它们是不同的类型。

回到示例中,在代码中

1
2
3
if"" then -- if""==true
    print"was true"
end

Lua测试""false还是nil,因为两者都不是,所以Lua会将条件视为真值。


免责声明:我没有lua的经验,这是有根据的猜测

这可能是因为"是一个空字符串,因此Lua可能会将其评估为长度为零的字符串。由于它是有效对象,因此不会等于true,false或nil,因此它将等于一个字符串长度为零。


免责声明:我对Lua唯一了解的是我对Lua一无所知。

看起来Lua使用==和在控制结构(ifwhilefor等)中完成的比较来对待相等比较。

根据Lua 5.1手册(第2.4.4节,控制结构),

The condition expression of a control structure can return any value.
Both false and nil are considered false. All values different from nil
and false are considered true (in particular, the number 0 and the
empty string are also true).

看来这与您所看到的一致。那是:

1
2
3
"" == false => false
"" == true => false
"" == nil => false

因为比较运算符似乎正在检查类型和值。

但是,如果在控件结构的条件中使用变量,则行为会稍有不同。那是,

1
2
3
if"" then
    print"Hello world!"
end

由于空字符串不同于nilfalse,因此将打印Hello world!,从而得出真值。