string.lua 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  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. -- Capitalize the first letter of the string.
  8. --
  9. function string.capitalized(self)
  10. return self:gsub("^%l", string.upper)
  11. end
  12. --
  13. -- Returns true if the string has a match for the plain specified pattern
  14. --
  15. function string.contains(s, match)
  16. return string.find(s, match, 1, true) ~= nil
  17. end
  18. --
  19. -- Returns an array of strings, each of which is a substring of s
  20. -- formed by splitting on boundaries formed by `pattern`.
  21. --
  22. function string.explode(s, pattern, plain, maxTokens)
  23. if (pattern == '') then return false end
  24. local pos = 0
  25. local arr = { }
  26. for st,sp in function() return s:find(pattern, pos, plain) end do
  27. table.insert(arr, s:sub(pos, st-1))
  28. pos = sp + 1
  29. if maxTokens ~= nil and maxTokens > 0 then
  30. maxTokens = maxTokens - 1
  31. if maxTokens == 0 then
  32. break
  33. end
  34. end
  35. end
  36. table.insert(arr, s:sub(pos))
  37. return arr
  38. end
  39. --
  40. -- Find the last instance of a pattern in a string.
  41. --
  42. function string.findlast(s, pattern, plain)
  43. local curr = 0
  44. repeat
  45. local next = s:find(pattern, curr + 1, plain)
  46. if (next) then curr = next end
  47. until (not next)
  48. if (curr > 0) then
  49. return curr
  50. end
  51. end
  52. --
  53. -- Returns the number of lines of text contained by the string.
  54. --
  55. function string.lines(s)
  56. local trailing, n = s:gsub('.-\n', '')
  57. if #trailing > 0 then
  58. n = n + 1
  59. end
  60. return n
  61. end
  62. ---
  63. -- Return a plural version of a string.
  64. ---
  65. function string:plural()
  66. if self:endswith("y") then
  67. return self:sub(1, #self - 1) .. "ies"
  68. else
  69. return self .. "s"
  70. end
  71. end
  72. ---
  73. -- Returns the string escaped for Lua patterns.
  74. ---
  75. function string.escapepattern(s)
  76. return s:gsub("[%(%)%.%%%+%-%*%?%[%]%^%$]", "%%%0")
  77. end