1. 程式人生 > >lua --- 邏輯運算符小結

lua --- 邏輯運算符小結

not lua 如果 小結 其他 語言 class div 返回

lua中的邏輯運算符,認為只有false、nil為假,其他的都為真(包括0、空串)

a and b   -- 如果a為false,則返回a,否則返回b
a or b    -- 如果a為true,則返回a,否則返回b

1 print(4 and 5)           --5
2 print(nil and 12)        --nil
3 print(false and 13)      --false
4 print(4 or 5)            --4
5 print(false or 5)        --5

一個很實用的技巧:如果x為false或者nil則給x賦初始值v

x = x or v

等價於

if not x then
    x = v
end

C語言中的三元運算符

a ? b : c

在Lua中可以這樣實現:

(a and b) or c

lua --- 邏輯運算符小結