Last active
January 9, 2026 18:03
-
-
Save bytejon/799775a088545a42e8d3646e3adbbf9b to your computer and use it in GitHub Desktop.
Luau utility for string.split behavior with support for more than one delimiter
This file contains hidden or 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
| -- jonbyte, 2026 | |
| local function split( | |
| input: string, -- string to be split | |
| sep: { string }, -- array of separator strings | |
| include: true? -- if separators should be included in result | |
| ) | |
| if #sep == 0 then | |
| -- early exit: there is nothing to split the string | |
| return { input } | |
| end | |
| local result: { string } = {} | |
| local len = #input | |
| local i = 1 | |
| repeat | |
| local k = 0 -- offset to exclude first character of found separator from plain substring | |
| local w = 0 -- 0-based width of separator string if found | |
| local j = len -- upper bound of substring | |
| local s: string? -- separator string if found on this pass | |
| for _, v in sep do | |
| local a, b = string.find(input, v, i, true) | |
| if a and a <= j then | |
| s = v -- the separator string | |
| j = a | |
| w = b - a -- we add 1 later | |
| k = -1 | |
| end | |
| end | |
| local sub = string.sub(input, i, j+k) | |
| table.insert(result, sub) | |
| if include and s then | |
| table.insert(result, s) | |
| end | |
| i = j + w + 1 | |
| until s == nil | |
| return result | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment