Lua 中的 and 和 or 是不同于 C 语言的。在 C 语言中,and 和 or 只得到两个值 1 和 0,其中 1 表示真,0 表示假。而 Lua 中 and 的执行过程是这样的:
a and b:
若 a 为 nil 或 false,b 为任意的值,则返回 a (即 nil 或 false) (短路求值)
若 a 为真值,则返回 b 的那个值。
a or b:
若 a 为 nil 或 false,b 为任意的值,则返回 b
若 a 为真值,则返回 a 的那个值(短路求值)。
示例代码:test3.lua
local c = nil
local d = 0
local e = 100
local f = false
----------- and -----------
print(c and d) -->打印 nil
print(d and c) -->打印 nil
print(c and e) -->打印 nil
print(e and c) -->打印 nil
print(c and f) -->打印 nil
print(f and c) -->打印 false
print(d and e) -->打印 100
print(e and d) -->打印 0
print(d and f) -->打印 false
print(f and d) -->打印 false
----------- or -----------
print(c or d) -->打印 0
print(d or c) -->打印 0
print(c or e) -->打印 100
print(e or c) -->打印 100
print(c or f) -->打印 false
print(f or c) -->打印 nil
print(d or e) -->打印 0
print(e or d) -->打印 100
print(d or f) -->打印 0
print(f or d) -->打印 0
----------- not -----------
print(not c) -->打印 true
print(not d) -->打印 false
print(not e) -->打印 false
print(not f) -->打印 true
local a, b = 1, 2
local x, y = 3, 4
local i = 10
local res = 0
res = a + i < b/2 + 1 -->等价于res = (a + i) < ((b/2) + 1)
res = 5 + x^2*8 -->等价于res = 5 + ((x^2) * 8)
res = a < y and y <=x -->等价于res = (a < y) and (y <= x)