-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathstringbuilder.lua
108 lines (92 loc) · 2.47 KB
/
stringbuilder.lua
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
---
--- StringBuilder v0.2 by yangruihan
--- See https://github.com/RayStudio36/StringBuilder.lua for usage documentation.
--- Licensed under MIT.
--- See https://opensource.org/licenses/MIT for details.
---
---@class StringBuilder
local StringBuilder = {}
StringBuilder.__index = StringBuilder
setmetatable(
StringBuilder,
{
__call = function(class, ...)
local instance = {}
setmetatable(instance, StringBuilder)
instance:new(...)
return instance
end
}
)
function StringBuilder:new()
self._buffer = {}
end
function StringBuilder:append(...)
for i = 1, select("#", ...) do
table.insert(self._buffer, tostring(select(i, ...)))
end
return self
end
---@param format string
function StringBuilder:append_format(format, ...)
table.insert(self._buffer, format:format(...))
end
function StringBuilder:append_line(...)
local len = select("#", ...)
if len > 0 then
for i = 1, len do
table.insert(self._buffer, tostring(select(i, ...)))
table.insert(self._buffer, "\n")
end
else
table.insert(self._buffer, "\n")
end
return self
end
---@param array table
---@param seperator string
function StringBuilder:append_array(array, seperator)
if not array then
return self
end
seperator = seperator or ", "
for i, v in ipairs(array) do
if i == #array then
table.insert(self._buffer, string.format("%d: %s", i, tostring(v)))
else
table.insert(self._buffer, string.format("%d: %s%s", i, tostring(v), seperator))
end
end
return self
end
---@param t table
---@param seperator string
function StringBuilder:append_table(t, seperator)
if not t then
return self
end
local cnt = 0
seperator = seperator or ", "
for k, v in pairs(t) do
cnt = cnt + 1
table.insert(self._buffer, string.format("{%s: %s}%s", tostring(k), tostring(v), seperator))
end
if cnt > 0 then
local last_str = self._buffer[#self._buffer]
self._buffer[#self._buffer] = last_str:sub(1, #last_str - #seperator)
end
return self
end
---@param clear boolean will clear buffer, default false
function StringBuilder:tostring(clear)
clear = clear or false
local ret = table.concat(self._buffer)
if clear then
self:clear()
end
return ret
end
function StringBuilder:clear()
self._buffer = {}
end
return StringBuilder