asciichunks

function asciichunks( str [, length] ) --> chunks

Description

Splits a the string str into smaller chunks with a maximum size. The default value of length is 1.

Note
asciichunks will split into bytes, rather than characters when dealing with a multi-byte encoded string.

Parameters

str

The string that should be chunked.

length

The optional chunk length. The default value is 1.

Return Values

chunks

Array table with the generated chunks.

Code

--ZFUNC-asciichunks-v1
local function asciichunks( str, length ) --> chunks
   length = length or 1
   local chunks = {}

   local i = 1
   local last = string.len( str )
   while i <= last do
      local j = i + length - 1
      table.insert( chunks, str:sub( i, j ) )
      i = i + length
   end

   return chunks
end

return asciichunks

Examples

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

chunks = asciichunks( "abc", 2 )
t.is( "ab", chunks[ 1 ] )
t.is( "c", chunks[ 2 ] )

chunks = asciichunks( "abc" )
t.is( "a", chunks[ 1 ] )
t.is( "b", chunks[ 2 ] )
t.is( "c", chunks[ 3 ] )

t.done()

Inspired by