[strings] Add utility to test whether a path is absolute

This commit is contained in:
Lorenzo Cogotti 2023-09-23 16:03:12 +02:00
parent 12a12197df
commit 9fa38d17a2
1 changed files with 22 additions and 0 deletions

View File

@ -155,6 +155,28 @@ function strings.splitpath(path)
return path:match("(.-)([^\\/]-)(%.?[^%.\\/]*)$")
end
--- Test whether the path is absolute.
--
-- @string path a path to be tested
-- @string[opt] sep separator pattern, '/' for Unix, '\\' for Windows, if none is provided, path is tested for both
-- @treturn boolean true if path is absolute, false otherwise
function strings.isabspath(path, sep)
if sep == nil then
-- Conservative test, both Unix-style and Windows-style
return strings.isabspath(path, '/') or strings.isabspath(path, '\\')
elseif sep == '/' then
-- Unix-style
return #path >= 1 and path:byte(1) == SLASH
elseif sep == '\\' then
-- Windows-style
return
(#path >= 1 and path:byte(1) == BACKSLASH) or
(#path >= 3 and path:byte(2) == COLON and path:byte(3) == BACKSLASH)
else
error(("Unsupported separator pattern: %q"):format(sep))
end
end
--- Test whether a string starts with a prefix.
--
-- This is an optimized version of: return s:sub(1, #prefix) == prefix.