Ray Lee | 李宗叡
Learn or Die
Published in
Nov 18, 2023

# 前言

簡單記錄一下 lua 中 string.gmatch 的用法

# 格式

簡單的說,arg1 為 string,arg2 為 pattern,會依據 arg2 的 pattern as delimiter 來 split string

需特別注意的是,string.gmatch() 返回的是一個 function,每次執行這個 function 會依序的回傳 該 string 的 split

如果放在 loop 裡面就會自動地被執行

loop example

EVAL "
local t = 'a,b,c'
local result = ''
for key in string.gmatch(t, '([^,]+)') do result = result .. key end
return result
" 0

上面的輸出是 ‘abc’,也可以在 do 裡面把 string 轉成 array

non loop example

EVAL "
local t = {}

local first = string.gmatch(t, '([^,]+)')

local result = first()
return result
" 0

所以每次執行 first() 都會拿到下一個 split string

# 參考資料

Ray Lee | 李宗叡
Learn or Die

It's Ray. I do both backend and frontend, but more focus on backend. I like coding, and would like to see the whole picture of a product.