lua - 为什么 "not nil"在 Lua 中返回 true?

标签 lua boolean-logic

我使用 repl.it 来查看它返回的内容,只是出于好奇,结果发现 不是零 返回 true

为什么会这样?是不是因为在 Lua 中一切最终都应该是对的还是错的?

Repl.it 链接:https://repl.it/repls/SanePastelHarrier

最佳答案

因为 nil 在转换为 bool 值时是 false:

2.2 Booleans

The boolean type has two values, false and true, which represent the traditional boolean values. However, booleans do not hold a monopoly of condition values: in Lua, any value may represent a condition. Conditionals (such as the ones in control structures) consider both false and nil as false and anything else as true. Beware that, unlike some other scripting languages, Lua considers both zero and the empty string as true in conditional tests.

not 将其参数视为 bool 值:

3.3 Logical Operators

The logical operators areand, or, and not. Like control structures, all logical operators consider both false and nil as false, and anything else as true.

关于lua - 为什么 "not nil"在 Lua 中返回 true?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47963048/

相关文章:

c++ - 带有 bool 逻辑的单个返回是否等同于保护子句?

boolean-logic - bool 代数简化

if-statement - Mathematica If-then 与 Implies

list - Lua 语言 : how use something similar to python list comprehensions

Lua:我需要在 if 中重复变量吗?

lua - math.randomseed(os.time())中的语法错误

c - Lua 5.2 C API 和要求

未调用 Lua 元方法

c++ - C++11 或 C++14 是否支持三值或多值逻辑?

conditional - 我可以简化这个使用逻辑否定运算符的条件语句吗?