Last active
April 10, 2026 02:34
-
-
Save amekusa/deeeda30251167664fe2ab8f6e22bb39 to your computer and use it in GitHub Desktop.
Split the given string into pieces separated by the given separator.
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
| local function trim(str) | |
| return match(str, '^()%s*$') and '' or match(str, '^%s*(.*%S)') | |
| end | |
| -- @author Satoshi Soma (github.com/amekusa) | |
| -- @param {string} str - String to split | |
| -- @param {string} sep - Separator | |
| -- @param {boolean} plain - Whether the separator is a plain string, or a pattern | |
| -- @return {table} Array of pieces of the string | |
| local function split(str, sep, plain) | |
| if #sep == 0 then | |
| return {str} | |
| end | |
| local find = string.find | |
| local sub = string.sub | |
| local insert = table.insert | |
| local r = {} | |
| local len = #str | |
| local next = 1 | |
| local found, last, item | |
| repeat | |
| found, last = find(str, sep, next, plain) | |
| if not found then | |
| found = len + 1 | |
| last = found | |
| end | |
| item = trim(sub(str, next, found - 1)) | |
| if #item > 0 then | |
| insert(r, item) | |
| end | |
| next = last + 1 | |
| until next > len | |
| return r | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment