Skip to content

Instantly share code, notes, and snippets.

@denisdemaisbr
Last active June 23, 2023 11:26
Show Gist options
  • Save denisdemaisbr/b90a4dd8c2257c319bf9199c68a8583d to your computer and use it in GitHub Desktop.
Save denisdemaisbr/b90a4dd8c2257c319bf9199c68a8583d to your computer and use it in GitHub Desktop.
split a string by length like str_split() from php ported to lua
--
-- based on https://www.php.net/manual/en/function.str-split.php
-- feel to free to validate/adjust to uses asserto/error
--
-- Denis Dos Santos Silva
--
local function str_split(str, length)
local result = {}
local index = 1
if (type(str) ~= 'string') then return result; end
if (not length) then length=1; end
if (length <= 0) then return result; end
if (length > slen) then return result; end
local slen = #str;
while index <= slen do
table.insert(result, string.sub(str, index, index + length - 1))
index = index + length
end
return result
end
return str_split
local str_split = require 'str_split'
local s = 'hello world'
for i=1, #s do
print( table.concat(str_split(s, i), '-') )
end
print( table.concat(str_split(s), '-') )
print( table.concat(str_split(s, #s), '-') )
print( table.concat(str_split(s, #s+1), '-') )
print( table.concat(str_split(s, 0), '-') )
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment