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( "taptest" )
local asciichunks = require( "asciichunks" )

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

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

t()

Inspired by