rightpad

function rightpad( str, len [, c [, trunc]] ) --> str

Description

Pads str on the right side if it’s shorter than len. It is possible to truncate string values that are longer than len.

Parameters

str

The string to pad.

len

The padding length.

c

Optional char value used for the padding. The default value is a space character(U+0020).

trunc

Optional bool parameter that allows to truncate to long result strings. The default value is false.

Return Values

str

The padded string.

Code

--ZFUNC-rightpad-v1
local function rightpad( str, len, c, trunc ) --> str
   c = c or " "
   local r = len - #str
   if r > 0 then
      str = str..string.rep( c, r )
   end
   if trunc then
      str = str:sub( 1, len )
   end
   return str
end

return rightpad

Examples

local t = require( "tapered" )
local rightpad = require( "rightpad" )

t.is( "foo  ", rightpad( "foo", 5 ) )
t.is( "foo", rightpad( "foo", 3 ) )

t.is( "foobar", rightpad( "foobar", 5 ) )
t.is( "fooba", rightpad( "foobar", 5, " ", true ) )

t.is( "1..", rightpad( tostring( 1 ), 3, "." ) )

t.done()

See also