OpenResty實戰-Lua入門-表達式

OpenResty實戰-Lua入門-表達式

算術運算符

Lua 的算術運算符如下表所示:

OpenResty實戰-Lua入門-表達式

示例代碼:test1.lua

print(1 + 2) -->打印 3

print(5 / 10) -->打印 0.5。 這是Lua不同於c語言的

print(5.0 / 10) -->打印 0.5。 浮點數相除的結果是浮點數

-- print(10 / 0) -->注意除數不能為0,計算的結果會出錯

print(2 ^ 10) -->打印 1024。 求2的10次方

local num = 1357

print(num % 2) -->打印 1

print((num % 2) == 1) -->打印 true。 判斷num是否為奇數

print((num % 5) == 0) -->打印 false。判斷num是否能被5整數

關係運算符

OpenResty實戰-Lua入門-表達式

示例代碼:test2.lua

print(1 < 2) -->打印 true

print(1 == 2) -->打印 false

print(1 ~= 2) -->打印 true

local a, b = true, false

print(a == b) -->打印 false

注意:Lua 語言中“不等於”運算符的寫法為:~=

在使用“==”做等於判斷時,要注意對於 table, userdate 和函數, Lua 是作引用比較的。

也就是說,只有當兩個變量引用同一個對象時,才認為它們相等。可以看下面的例子:

local a = { x = 1, y = 0}

local b = { x = 1, y = 0}

if a == b then

print("a==b")

else

print("a~=b")

end

---output:

a~=b

由於 Lua 字符串總是會被“內化”,即相同內容的字符串只會被保存一份,因此 Lua 字符串之間的相等性比較可以簡化為其內部存儲地址的比較。這意味著 Lua 字符串的相等性比較總是為 O(1). 而在其他編程語言中,字符串的相等性比較則通常為 O(n),即需要逐個字節(或按若干個連續字節) 進行比較。

邏輯運算符

OpenResty實戰-Lua入門-表達式

Lua 中的 and 和 or 是不同於 c 語言的。在 c 語言中,and 和 or 只得到兩個值 1 和 0,其中 1表示真,0 表示假。而 Lua 中 and 的執行過程是這樣的:

a and b 如果 a 為 nil,則返回 a,否則返回 b;

a or b 如果 a 為 nil,則返回 b,否則返回 a。

示例代碼:test3.lua

local c = nil

local d = 0

local e = 100

print(c and d) -->打印 nil

print(c and e) -->打印 nil

print(d and e) -->打印 100

print(c or d) -->打印 0

print(c or e) -->打印 100

print(not c) -->打印 true

print(not d) -->打印 false

注意:所有邏輯操作符將 false 和 nil 視作假,其他任何值視作真,對於 and 和 or,“短路求值”,對於 not,永遠只返回 true 或者 false。

字符串連接

在 Lua 中連接兩個字符串,可以使用操作符“..”(兩個點) 。如果其任意一個操作數是數字的話,Lua 會將這個數字轉換成字符串。注意,連接操作符只會創建一個新字符串,而不會改變原操作數。也可以使用 string 庫函數 string.format 連接字符串。

print("Hello " .. "World") -->打印 Hello World

print(0 .. 1) -->打印 01

str1 = string.format("%s-%s","hello","world")

print(str1) -->打印 hello-world

str2 = string.format("%d-%s-%.2f",123,"world",1.21)

print(str2) -->打印 123-world-1.21

由於 Lua 字符串本質上是隻讀的,因此字符串連接運算符幾乎總會創建一個新的(更大的)字符串。這意味著如果有很多這樣的連接操作(比如在循環中使用 .. 來拼接最終結果) ,則性能損耗會非常大。在這種情況下,推薦使用 table 和 table.concat() 來進行很多字符串的拼接,例如:

local pieces = {}

for i, elem in ipairs(my_list) do

pieces[i] = my_process(elem)

end

local res = table.concat(pieces)

當然,上面的例子還可以使用 LuaJIT 獨有的 table.new 來恰當地初始化 pieces 表的空間,以避免該表的動態生長。這個特性我們在後續文章還會詳細討論。

優先級

Lua 操作符的優先級如下表所示(從高到低):

OpenResty實戰-Lua入門-表達式

示例:

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)

若不確定某些操作符的優先級,就應顯示地用括號來指定運算順序。這樣做還可以提高代碼的可讀

至此,Lua入門之表達式就介紹完了。下一篇將介紹Lua入門之控制結構。

後續計劃內容:

Lua入門+高階

Nginx

OpenResty

LuaRestyRedisLibrary

LuaCjsonLibrary

PostgresNginxModule

LuaNginxModule

LuaRestyDNSLibrary

LuaRestyLock

stream_lua_module

balancer_by_lua

OpenResty 與 SSL

測試

Web服務

火焰圖

OpenResty周邊

零碎知識點


分享到:


相關文章: