官术网_书友最值得收藏!

Logical operators

Logical operators test the relationship of two statements. Logical operators work a little differently in Lua than in other languages. In Lua, anything not false is considered to be true. Only two values represent false for a logical operator, the constant value of false and nil; anything else is true.

Logical operators in Lua do not evaluate to a Boolean result; rather they evaluate to one of the provided operands.

The and operator returns its first operand if that operand is false and the second operand if the first operand was true. Here is an example:

x = true and false -- value is false
y = false and false -- value is false
z = true and true -- value is true
w = 7 and 1 -- value is 1

The or operator (or) returns its second operand if it is not false, otherwise it will return the first operand. Here is an example:

x = true or false -- value is true
y = false or false -- value is false
z = true or true -- value is true
w = 7 or 1 -- value is 7

The and/or operators both use shortcut evaluation. This means that the second operand is only evaluated if needed. This is important when the operands are functions. Here is an example:

function TrueFunction()
print ("returning true")
return true
end

function FalseFunction()
print ("returning false")
return false
end

x = FalseFunction() and TrueFunction()

This statement only evaluates the false function. Only returning false is printed. But if we changed the line that assigns x to be the following:

x = TrueFunction() and FalseFunction()

After changing the line, both functions will evaluate, and both returning true and returning false will be printed. Shortcut evaluation can make bugs difficult to spot; for this reason, try to avoid functions as operands when using logical operators.

The logical not operator is a unary operator. It reverses the logical state of its operand. Provided with a value that is false, this operator will evaluate to true. Provided with a value that is true, the operator evaluates to false. Here is an example:

x = not true -- false
y = not true or false -- false
z = not not false -- false
w = not (7 + 1) -- false
主站蜘蛛池模板: 阳西县| 云龙县| 菏泽市| 金溪县| 镇江市| 丹棱县| 沙河市| 巴马| 会东县| 东辽县| 云梦县| 甘泉县| 义马市| 诸城市| 北票市| 兴宁市| 体育| 喀喇沁旗| 嫩江县| 商都县| 手机| 区。| 百色市| 谢通门县| 乐安县| 新绛县| 鹤山市| 浮山县| 涪陵区| 台东县| 广饶县| 锦屏县| 泸溪县| 磐安县| 大名县| 两当县| 永新县| 平邑县| 玛曲县| 永川市| 大理市|