Skip to content

Commit 38ee36d

Browse files
authored
Update ansi.luau
1 parent df9c063 commit 38ee36d

File tree

1 file changed

+28
-15
lines changed

1 file changed

+28
-15
lines changed

batteries/ansi.luau

Lines changed: 28 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,27 +1,40 @@
1-
local function replaceClose(str: string, close: string, replace: string, index: number?): string
2-
local result = ""
1+
local RESULT_TBL = {}
2+
3+
local function replaceClose(
4+
str: string, close: string, replace: string, index: number, closeLen: number
5+
): string
36
local cursor = 1
7+
local tblLen = 0
8+
49
while index do
5-
result ..= string.sub(str, cursor, index - 1) .. replace
6-
cursor = index + #close
7-
local nextIndex = string.find(str, close, cursor, true)
8-
index = nextIndex
10+
tblLen += 1
11+
-- not using table.insert because its likely the index would already be allocated
12+
RESULT_TBL[tblLen] = string.sub(str, cursor, index - 1)
13+
cursor = index + closeLen
14+
index = string.find(str, close, cursor, true)
915
end
10-
return result .. string.sub(str, cursor)
16+
local result = table.concat(RESULT_TBL, replace)
17+
table.clear(RESULT_TBL)
18+
19+
return `{result}{string.sub(str, cursor)}`
1120
end
1221

1322
local function formatter(open: string, close: string, replace: string?): (string) -> string
23+
local closeLen = #close
24+
local openLen = #open
25+
replace = replace or open
26+
local format = `{open}%*{close}`
27+
1428
return function(str: string): string
15-
local index = string.find(str, close, #open + 1, true)
16-
if index then
17-
return open .. replaceClose(str, close, replace or open, index) .. close
18-
else
19-
return open .. str .. close
20-
end
29+
local index = string.find(str, close, openLen + 1, true)
30+
31+
return string.format(
32+
format, if index then replaceClose(str, close, replace, index, closeLen) else str
33+
)
2134
end
2235
end
2336

24-
return {
37+
return table.freeze({
2538
reset = formatter("\x1b[0m", "\x1b[0m"),
2639
bold = formatter("\x1b[1m", "\x1b[22m", "\x1b[22m\x1b[1m"),
2740
dim = formatter("\x1b[2m", "\x1b[22m", "\x1b[22m\x1b[2m"),
@@ -67,4 +80,4 @@ return {
6780
bgMagentaBright = formatter("\x1b[105m", "\x1b[49m"),
6881
bgCyanBright = formatter("\x1b[106m", "\x1b[49m"),
6982
bgWhiteBright = formatter("\x1b[107m", "\x1b[49m"),
70-
}
83+
})

0 commit comments

Comments
 (0)