- Lua Quick Start Guide
- Gabor Szauer
- 380字
- 2021-08-05 10:30:41
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.
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
- Mastering Visual Studio 2017
- 無代碼編程:用云表搭建企業數字化管理平臺
- Learning ASP.NET Core 2.0
- Learning Informatica PowerCenter 10.x(Second Edition)
- Python神經網絡項目實戰
- Linux環境編程:從應用到內核
- AutoCAD 2009實訓指導
- Webpack實戰:入門、進階與調優(第2版)
- ASP.NET 4.0 Web程序設計
- Hands-On Robotics Programming with C++
- 分布式架構原理與實踐
- Java程序設計實用教程(第2版)
- 計算機常用算法與程序設計教程(第2版)
- INSTANT EaselJS Starter
- Kotlin程序員面試算法寶典