Last active
June 23, 2023 11:26
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- | |
-- 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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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