Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find the last index of a character in a string

Tags:

string

lua

I want to have ability to use a lastIndexOf method for the strings in my Lua (Luvit) project. Unfortunately there's no such method built-in and I'm bit stuck now.

In Javascript it looks like:

'my.string.here.'.lastIndexOf('.')     // returns 14
like image 701
Kosmetika Avatar asked Dec 08 '13 22:12

Kosmetika


1 Answers

function findLast(haystack, needle)
    local i=haystack:match(".*"..needle.."()")
    if i==nil then return nil else return i-1 end
end
s='my.string.here.'
print(findLast(s,"%."))
print(findLast(s,"e"))

Note that to find . you need to escape it.

like image 77
lhf Avatar answered Oct 15 '22 09:10

lhf