leftpad

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

Description

Pads str on the left 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-leftpad-v1
local function leftpad( str, len, c, trunc ) --> str
   c = c or " "
   local r = len - #str
   if r > 0 then
      str = string.rep( c, r )..str
   end
   if trunc then
      str = str:sub( 1, len )
   end
   return str
end

return leftpad

Examples

local t = require( "taptest" )
local leftpad = require( "leftpad" )

t( leftpad( "foo", 5 ), "  foo" )
t( leftpad( "foo", 3 ), "foo" )

t( leftpad( "foobar", 5 ), "foobar" )
t( leftpad( "foobar", 5, " ", true ), "fooba" )

t( leftpad( tostring( 1 ), 2, "0" ), "01" )

t()

See also