1-- 2-- string.lua 3-- Additions to Lua's built-in string functions. 4-- Copyright (c) 2002-2013 Jason Perkins and the Premake project 5-- 6 7 8-- 9-- Capitalize the first letter of the string. 10-- 11 12 function string.capitalized(self) 13 return self:gsub("^%l", string.upper) 14 end 15 16 17 18-- 19-- Returns true if the string has a match for the plain specified pattern 20-- 21 22 function string.contains(s, match) 23 return string.find(s, match, 1, true) ~= nil 24 end 25 26 27-- 28-- Returns an array of strings, each of which is a substring of s 29-- formed by splitting on boundaries formed by `pattern`. 30-- 31 32 function string.explode(s, pattern, plain, maxTokens) 33 if (pattern == '') then return false end 34 local pos = 0 35 local arr = { } 36 for st,sp in function() return s:find(pattern, pos, plain) end do 37 table.insert(arr, s:sub(pos, st-1)) 38 pos = sp + 1 39 if maxTokens ~= nil and maxTokens > 0 then 40 maxTokens = maxTokens - 1 41 if maxTokens == 0 then 42 break 43 end 44 end 45 end 46 table.insert(arr, s:sub(pos)) 47 return arr 48 end 49 50 51 52-- 53-- Find the last instance of a pattern in a string. 54-- 55 56 function string.findlast(s, pattern, plain) 57 local curr = 0 58 repeat 59 local next = s:find(pattern, curr + 1, plain) 60 if (next) then curr = next end 61 until (not next) 62 if (curr > 0) then 63 return curr 64 end 65 end 66 67 68 69-- 70-- Returns the number of lines of text contained by the string. 71-- 72 73 function string.lines(s) 74 local trailing, n = s:gsub('.-\n', '') 75 if #trailing > 0 then 76 n = n + 1 77 end 78 return n 79 end 80 81 82 83--- 84-- Return a plural version of a string. 85--- 86 87 function string:plural() 88 if self:endswith("y") then 89 return self:sub(1, #self - 1) .. "ies" 90 else 91 return self .. "s" 92 end 93 end 94 95 96 97--- 98-- Returns the string escaped for Lua patterns. 99--- 100 101 function string.escapepattern(s) 102 return s:gsub("[%(%)%.%%%+%-%*%?%[%]%^%$]", "%%%0") 103 end 104