Debian Codegraph @

lua/include/string.lua

raw symbols SCIP
1 --[[
2 Copyright (C) 2014 HarpyWar ([email protected])
3
4 This file is a part of the PvPGN Project http://pvpgn.pro
5 Licensed under the same terms as Lua itself.
6 ]]--
7
8
9 -- Split text into table by delimeter
10 -- Usage example: string.split("one,two",",")
11 function string:split(str, sep)
12 str = str or '%s+'
13 local st, g = 1, self:gmatch("()("..str..")")
14 local function getter(segs, seps, sep, cap1, ...)
15 st = sep and seps + #sep
16 return self:sub(segs, (seps or 0) - 1), cap1 or sep, ...
17 end
18 return function() if st then return getter(st, g()) end end
19 end
20
21 -- Check string is nil or empty
22 -- bool
23 -- Usage example: string:empty("") -> true, string:empty(nil) -> true
24 function string:empty(str)
25 return str == nil or str == ''
26 end
27
28 -- bool
29 function string.starts(str, starts)
30 if string:empty(str) then return false end
31 return string.sub(str,1,string.len(starts))==starts
32 end
33
34 -- bool
35 function string.ends(str, ends)
36 if string:empty(str) then return false end
37 return ends=='' or string.sub(str,-string.len(ends))==ends
38 end
39
40 -- Replace string
41 -- Usage example: string.replace("hello world","world","Joe") -> "hello Joe"
42 function string.replace(str, pattern, replacement)
43 if string:empty(str) then return str end
44 local s, n = string.gsub(str, pattern, replacement)
45 return s
46 end
47
48 function string:trim(str)
49 if string:empty(str) then return str end
50 return (str:gsub("^%s*(.-)%s*$", "%1"))
51 end
52
53
54
55 -- Replace char in specified position of string
56 function replace_char(pos, str, replacement)
57 if string:empty(str) then return str end
58 return str:sub(1, pos-1) .. replacement .. str:sub(pos+1)
59 end
60
61 -- return count of substr in str
62 function substr_count(str, substr)
63 local _, count = string.gsub(str, substr, "")
64 return count
65 end