Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split string in equal chunks in Lua

Tags:

string

lua

I need to split a string in equal sized chunks (where the last chunk can be smaller, if the strings length can't be divided without remainder).

Let's say I have a string with 2000 chars. I want to split this string in equal sized chunks of 500 chars, so I would end up with 4 strings of 500 chars.

How can this be done in Lua, when neither the length of the initial string is fixed, nor the chunk size?

Example

String: "0123456789" (Length = 10) should be splitted in strings of 3 characters

Result: "012", "345", "678", "9"

(doesn't matter if the result is in a table or returned by a iterator)

like image 712
Keeper Avatar asked Jan 30 '26 08:01

Keeper


1 Answers

local function splitByChunk(text, chunkSize)
    local s = {}
    for i=1, #text, chunkSize do
        s[#s+1] = text:sub(i,i+chunkSize - 1)
    end
    return s
end

-- usage example
local st = splitByChunk("0123456789",3)
for i,v in ipairs(st) do
   print(i, v)
end

-- outputs
-- 1    012
-- 2    345
-- 3    678
-- 4    9
like image 129
rsc Avatar answered Feb 03 '26 00:02

rsc



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!