forked from blitmap/lua-snippets
-
Notifications
You must be signed in to change notification settings - Fork 0
/
string-pad.lua
executable file
·37 lines (26 loc) · 758 Bytes
/
string-pad.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
#!/usr/bin/env lua
local srep = string.rep
module('pad')
-- all of these functions return their result and a boolean
-- to notify the caller if the string was even changed
-- pad the left side
lpad =
function (s, l, c)
local res = srep(c or ' ', l - #s) .. s
return res, res ~= s
end
-- pad the right side
rpad =
function (s, l, c)
local res = s .. srep(c or ' ', l - #s)
return res, res ~= s
end
-- pad on both sides (centering with left justification)
pad =
function (s, l, c)
c = c or ' '
local res1, stat1 = rpad(s, (l / 2) + #s, c) -- pad to half-length + the length of s
local res2, stat2 = lpad(res1, l, c) -- right-pad our left-padded string to the full length
return res2, stat1 or stat2
end
return _M