How do you get the last index of a character in a string in Lua?
"/some/path/to/some/file.txt"
How do I get the index of the last /
in the above string?
How do you get the last index of a character in a string in Lua?
"/some/path/to/some/file.txt"
How do I get the index of the last /
in the above string?
index = string.find(your_string, "/[^/]*$")
(Basically, find the position where the pattern "a forward slash, then zero or more things that aren't a forward slash, then the end of the string" occurs.)
This method is a bit more faster (it searches from the end of the string):
index = your_string:match'^.*()/'
Loops?!? Why would you need a loop for that? There's a 'reverse' native string function mind you, just apply it then get the first instance :) Follows a sample, to get the extension from a complete path:
function fileExtension(path)
local lastdotpos = (path:reverse()):find("%.")
return (path:sub(1 - lastdotpos))
end
You can do it in a single line of course, I split it in two for legibility's sake.
Here is a complete solution.
local function basename(path)
return path:sub(path:find("/[^/]*$") + 1)
end
local s = "/aa/bb/cc/dd/ee.txt"
local sep = "/"
local lastIndex = nil
local p = string.find(s, sep, 1)
lastIndex = p
while p do
p = string.find(s, sep, p + 1)
if p then
lastIndex = p
end
end
print(lastIndex)
You could continue find next value, until find nil,record last position