mirror of
https://codeberg.org/1414codeforge/gear.git
synced 2025-02-17 04:10:43 +01:00
35 lines
810 B
Lua
35 lines
810 B
Lua
--- Common functions for strings.
|
|
--
|
|
-- @module gear.strings
|
|
-- @copyright 2022 The DoubleFourteen Code Forge
|
|
-- @author Lorenzo Cogotti
|
|
|
|
local strings = {}
|
|
|
|
|
|
--- Test whether a string starts with a prefix.
|
|
function strings.startswith(s, prefix)
|
|
-- optimized version of: return s:sub(1, #prefix) == prefix
|
|
for i = 1,#prefix do
|
|
if s:byte(i) ~= prefix:byte(i) then
|
|
return false
|
|
end
|
|
end
|
|
return true
|
|
end
|
|
|
|
--- Test whether a string ends with a trailing suffix.
|
|
function strings.endswith(s, trailing)
|
|
-- optimized version of: return trailing == "" or s:sub(-#trailing) == trailing
|
|
local n1,n2 = #s,#trailing
|
|
|
|
for i = 0,n2-1 do
|
|
if s:byte(n1-i) ~= trailing:byte(n2-i) then
|
|
return false
|
|
end
|
|
end
|
|
return true
|
|
end
|
|
|
|
return strings
|