「Lua」06節-表達式

Lua算術運算符

Lua算術運算符主要有:加(+)、減(-)、乘(x)、除(/)、取模(%)、指數(^)。

print(1+2) -- 輸出:3
print(2/10) -- 輸出:0.2
print(5.0/10) -- 輸出:0.5
-- print(3/0) -- 除數不能為0,若為0則會報錯
print(2^2) -- 輸出:4

local num=123
print(num%2) -- 輸出:1
print((num%2)==1) -- 判斷num是否為奇數,輸出:true
print((num%2)==0) -- 判斷num是否為偶數,輸出:false

Lua關係運算符

Lua中關係運算符主要有:小於()、等於(==)、大於等於(>=)、小於等於(<=)、不等於(~=)

注意事項:

  • Lua中的不等於運算符為:~=,這點要注意
  • 在使用等於(==)比較兩個操作數時,若操作數是 table、function,Lua是拿它們的引用來進行比較的
  • Lua中兩個相同內容的字符串只會被保存一份,所以字符串的比較是拿其內存地址來比較的
local a={1,2}
local b={1,2}
if a==b then
print('a==b')

else
print('a~=b')
end -- 輸出:a~=b
local c='hello';
local d='hello';
if c==d then
print('c==d')
else
print('c~=d')
end -- 輸出:c==d

Lua邏輯運算符

Lua邏輯運算符主要有:邏輯與(and)、邏輯或(or)、邏輯非(not)。

local a=true
local b=false
local c=nil
local d=""
local e=0
print(a and b) -- false
print(a or b) -- true
print(a and c) -- nil
print(a and d) -- 輸出空字符串
print(c and d) -- nil
print(c and e) -- nil
print(c or d) -- 輸出空字符串
print(c or e) -- 0

Lua中邏輯運算符很“奇葩”,規則如下:

  • x and y ,若x為nil,則返回x,否則返回y
  • x or y ,若x為nil,則返回y,否則返回x
  • 對於and和or運算,短路求值
  • 對於not運算,永遠返回true或false

Lua字符串連接

  • 使用兩個點號(..)連接字符串,若其中有操作數是數值,則會自動轉為字符串
  • 也可以使用string庫的format()函數連接字符串
  • 字符串連接操作符不會改變原操作數,只會創建一個新的字符串
print('hello '..'world') -- 輸出:hello world
print(0 .. 1) -- 注意此處..前後需要空格,否則報錯;輸出:01
local str1=string.format('%s - %s','hello','world')
print(str1) --輸出:hello - world
local str2=string.format('%d,%s - %.2f',123,'hello',12.3)
print(str2) --輸出:123,hello - 12.30


分享到:


相關文章: