Skip to content

Instantly share code, notes, and snippets.

@rfl890
Last active June 9, 2023 20:15
Show Gist options
  • Save rfl890/7249313dfafd7d9fe6c28df9a60e6d42 to your computer and use it in GitHub Desktop.
Save rfl890/7249313dfafd7d9fe6c28df9a60e6d42 to your computer and use it in GitHub Desktop.
String.split with JavaScript-like behaviour in Lua
local function js_string_split(s, f)
local offset = 1
local nextOffset = 0
local result = {}
if not string.find(s, f) then
return { s }
end
if f == "" then
for i = 1, #s do
table.insert(result, s:sub(i, i))
end
return result
end
while true do
-- first token
local pos1, pos2 = string.find(s, f, offset, true)
if pos1 == nil then
break
end
-- before first token
local str_before = s:sub(offset, pos2 - #f)
table.insert(result, str_before)
offset = pos2 + 1
-- is this the last token?
local nextpos1, nextpos2 = string.find(s, f, offset, true)
if not nextpos1 then
local str_next = s:sub(offset, #s)
table.insert(result, str_next)
end
end
return result
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment