在來寫一個lua中實作php的strpos()函數,查找某個字元串在指定字元串首次出現的位置,其實lua中也為我們提供了這樣的函數使用string.find()即可獲得,下面我們還是簡單寫一個函數,代碼如下:
function strpos (str, f)
if str ~= nil and f ~= nil then
return (string.find(str, f))
else
return nil
end
end
測試如下圖所示:

下面在來個strrpos()函數,查找某個字元串在指定字元串最後一次出現的位置,下面我們還是簡單寫一下函數,代碼如下:
function strrpos (str, f)
if str ~= nil and f ~= nil then
local t = true
local offset = 1
local result = nil
while (t)
do
local tmp = string.find(str, f, offset)
if tmp ~= nil then
offset = offset + 1
result = tmp
else
t = false
end
end
return result
else
return nil
end
end
測試如下圖(注意:如果要查找 . 需要進行轉義,使用"%."):
好了,今天就先到這裡,以後我們繼續實作其他函數功能