string pad module

Send Snippet To: Save this snippet to Code Collector Pro -- view all roger's snippets
language: Other
license: Other

Code for Snippet:

                
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
comments powered by Disqus

Info

Link to this snippet:


Download to Code Collector

To use the direct link to your snippet on CodeCollector.net either copy the html from the above section or drag the Download to Code Collector to where you would like to use it.

More Info:

Times Viewed: 4
Date Added: 2018-01-09 04:42:04
Last Modified: 2018-01-10 09:54:13

Web Analytics